[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: mcmonkey4eva\n"
  },
  {
    "path": ".gitignore",
    "content": ".vscode/\nassets/*.yml\nassets/styles-user.css\n__pycache__/\nassets/images/**/*.png\nassets/images/**/*.jpg\nassets/images/**/*.webp\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2022-2023 Alex \"mcmonkey\" Goodwin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Stable Diffusion Infinity Grid Generator\n\n![img](github/megagrid_ref.png)\n\n### Concept\n\nExtension for the [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) that generates infinite-dimensional grids.\n\nAn \"infinite axis grid\" is like an X/Y plot grid, but with, well, more axes on it. Of course, monitors are 2D, so this is implemented in practice by generating a webpage that lets you select which two primary axes to display, and then choose the current value for each of the other axes.\n\n### Goals and Use Cases\n\nThe primary goal is to let people generate their own fancy grids to explore how different settings affect their renders in a convenient form.\n\nAnother goal of this system is to develop educational charts, to provide a universal answer to the classic question of \"what does (X) setting do? But what about with (Y)?\" - [The MegaGrid](https://sd.mcmonkey.org/megagrid/). There is a built in ability to add description text to fields, for the specific purpose of enhancing educational page output.\n\n### Pros/Cons\n\nThe advantage of this design is it allows you to rapidly compare the results of different combinations of settings, without having to wait to for generation times for each specific sub-grid as-you-go - you just run it all once in advance (perhaps overnight for a large run), and then after that browse through it in realtime.\n\nThe disadvantage is that time to generate a grid is exponential - if you have 5 samplers, 5 seeds, 5 step counts, 5 CFG scales... that's 5^4, or 625 images. Add another variable with 5 options and now it's 3125 images. You can see how this quickly jumps from a two minute render to a two hour render.\n\n--------------\n\n### Table of Contents\n\n- [Examples](#Examples)\n- [Status](#Status)\n- [Installation](#Installation)\n- [Basic Usage](#Basic-Usage)\n- [Advanced Usage](#Advanced-Usage)\n    - [1: Grid Definition File](#1-grid-definition-file)\n    - [Supported Extensions](#supported-extensions)\n        - [Dynamic Thresholding (CFG Scale Fix)](#dynamic-thresholding-cfg-scale-fix)\n        - [ControlNet](#controlnet)\n    - [2: Grid Content Generation via WebUI](#2-grid-content-generation-via-webui)\n    - [3: Using The Output](#3-using-the-output)\n    - [4: Expanding Later](#4-expanding-later)\n- [Credits](#credits)\n- [Common Issues](#common-issues)\n- [License](#License)\n\n--------------\n\n### Examples\n\nHere's a big MegaGrid using almost every mode option in one, with detailed educational descriptions on every part: https://sd.mcmonkey.org/megagrid/\n\nHere's a very small web demo you can try to test how the output looks and works: https://mcmonkeyprojects.github.io/short_example and you can view the generated asset files for that demo [here](https://github.com/mcmonkeyprojects/mcmonkeyprojects.github.io/tree/master/short_example).\n\n![img](github/simple_ref.png)\n\n--------------\n\n### Status\n\nCurrent overall project status (as of December 2023): **Works well, actively maintained**. Has been generally well tested. The core has been ported to other environments and stress-tested for multiple real projects that depend on large grids and rapid grid analysis.\n\nA version of this project is also available for [StableSwarmUI, here](https://github.com/Stability-AI/StableSwarmUI/blob/master/src/BuiltinExtensions/GridGenerator/README.md) which also lets you use it with Comfy and other backends\n\n--------------\n\n### Installation\n\n- You must have the [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) already installed and working. Refer to that project's readme for help with that.\n- Open the WebUI, go to to the `Extensions` tab\n- -EITHER- Option **A**:\n    - go to the `Available` tab with\n    - click `Load from` (with the default list)\n    - Scroll down to find `Infinity Grid Generator`, or use `CTRL+F` to find it\n- -OR- Option **B**:\n    - Click on `Install from URL`\n    - Copy/paste this project's URL into the `URL for extension's git repository` textbox: `https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script`\n- Click `Install`\n- Restart or reload the WebUI\n\n--------------\n\n### Basic Usage\n\n![img](github/create_in_ui_demo.png)\n\n- Basic usage is very simple!\n    - select the script under `Scripts`\n    - Leave file as `Create in UI`\n    - Select `Axis 1 Mode` as whatever mode you want, like `Seed` or `Sampler`\n    - In the `Axis 1 Value` box, you can type a comma-separated list like `1, 2, 3`, or a double-pipe separated list like `1girl, booru style, prompt || 1boy, has commas, so pipes avoid problems`\n    - Repeat for as many axes as you want. When you configure axis #4, it will automatically add 4 more rows of axes to fill in. Leave any extras empty.\n    - Click your main `Generate` button and wait for it to finish.\n    - When it's done, click the button labeled `Page will be at (Click me) outputs/...` to view the full page.\n    - Note that a `config.yml` is saved in the output directory, which you can copy to your `assets` folder if you want to reuse it.\n\n--------------\n\n### Advanced Usage\n\nUsage comes in three main steps:\n- [1: Build a grid definition](#1-grid-definition-file)\n- [2: Generate its contents](#2-grid-content-generation-via-webui)\n- [3: View/use the generated output page](#3-using-the-output)\n- You can also [expand your grid later](#4-expanding-later)\n\n--------------\n\n### 1: Grid Definition File\n\n![img](github/yaml_settings_blur.png)\n\n- Grid information is defined by **YAML files**, in the extension folder under `assets`. Find the `assets/short_example.yml` file to see an example of the full format.\n\n**If you do not want to follow an example file:**\n- You can **create new files** in the assets directory (as long as the `.yml` extension stays), or copy/paste an example file and edit it. I recommend you do not edit the actual example file directly to avoid git issues.\n- I recommend editing with a **good text editor**, such as *VS Code* or *Notepad++*. Don't use *MS Word* or *Windows Notepad* as those might cause trouble.\n- All text inputs allow for **raw HTML**, so, be careful. You can use `&lt;` for `<`, and `&gt;` for `>`, `&#58;` for `:`, and `&amp;` for `&`.\n- The file must have key `grid`, with subkey `title` and `description` to define the file data.\n    - It must also have `format` as `jpg` or `png`\n    - It can optionally also have `params` to specify any default parameters.\n    - It can optionally define `show descriptions`, `autoscale`, and `sticky` as `true` or `false` to change default web-viewer settings.\n    - It can optionally define `x axis`, `y axis`, `x super axis`, and `y super axis` as axis IDs to change the default web-viewer axes.\n- The file can optionally have key `variables` with subkey/value pairs as replacements, for example `(type): waffle` - then later in a param value you can use `a picture of a (type)` to automatically fill the variable. These can be in any format you desire, as they are simple text replacements. They apply to all values, including titles, descriptions, and params (this was added for [valconius in issue #16](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/16)).\n- The file must have key `axes` to define the list of axes. This is a map-list key - meaning, add subkeys to create a list of each axis.\n    - The simplest format for an axis is a setting name as the key and a comma-separated list of values inside.\n        - For example, `seed: 1, 2, 3` is a valid and complete axis.\n        - If commas may be problematic, you many instead use two pipes `||` to separate values - for example `prompt: 1girl, booru style, commas || 1boy, more commas, etc`. If `||` is used, commas will be ignored for splitting\n        - For numeric inputs, you can use ellipses notation to quickly shorthand long lists. For example: `seed: 1, 2, ..., 10` automatically fills to `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`. Or, `cfg scale: 7.0, 7.1, ..., 7.8` automatically fills to `7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8`.\n            - Note that you must have two entries before and one after - the step rate is defined as the space between the two prior and the total range is defined as between the one prior and the one after.\n            - You can use ellipses multiple times in one set, for example `1, 2, ..., 6, 8, ... 14` will fill to `1, 2, 3, 4, 5, 6, 8, 10, 12, 14` (note how 1-6 are spaced 1 apart, but 6-14 are spaced two apart).\n    - Each axis must have a `title`, and `values`. It can optionally have a `description`.\n        - You can also optionally have `default: (value_id)` to set the default selected tab.\n        - There are two ways to do a value in the value list:\n            - Option 1: just do like `steps=10` ... this will set title to `10`, and param `steps` to value `10`, with no description.\n            - Option 2: Add a submapping with key `title`, and optional `description`, and then `params` as a sub map of parameters like `steps: 10`\n                - A value with a full format can be set to skip rendering via adding `skip: true`. This is useful for eg if some values are only valid in certain combinations, you can do runs with some skipped. Skipped values will be kept in the HTML output.\n                - A value may specify `show: false` to default uncheck the 'Show value' advanced option.\n\nMicro example:\n```yml\ngrid:\n    title: Tiny example\n    author: someone\n    description: This is just to show core format. View the example `.yml` files in assets for better examples.\n    format: jpg\naxes:\n    sampler: Euler, DDIM\n    seed: 1, 2, 3\n```\n\n- Names and descriptions can always be whatever you want, as HTML text.\n\n\n#### Settings supported for parameters\n\n| Name | Type | Example | Notes |\n| --- | --- | --- | ----------- |\n| `Sampler` | Named | `DDIM`, `euler`, ... | |\n| `Model` | Filename | `sd-v1-5` | Note that `Model` and `VAE` are **global settings**, and as such you should not have an axis where some values specify one of those params but others don't, as this will cause an unpredictable model selection for the values that lack specificity. |\n| `VAE` | Filename | `kl-f8-anime2` | See note on `Model` above |\n| `Prompt` | Text | `a cat` | |\n| `Negative Prompt` | Text | `gross, weird, bad` | |\n| `Prompt Replace` | Text-Pair | `some_tag = new text here` | Note the `=` symbol to separate the original text with the new text. That will change a prompt of for example `my prompt with some_tag stuff` to `my prompt with new text here stuff`.<br>Unlike other modes, the PromptReplace is case-sensitive - if you use capitals in your prompt, you need capitals in your replace matcher.<br>If you want multiple replacements in one value, you can number them, like `Prompt Replace 1` and `Prompt Replace 2` and etc.<br>When building a simple list in UI, you can just do eg `cat, dog, waffle` and it will understand to replace `cat` in the base prompt first with `cat`, then `dog`, then `waffle` (ie you can skip the `=` for simple usages). |\n| `Styles` | Text | `photo`, `cartoon`, ... | Automatically includes UI styles to your prompt. Can use comma-separated list to have multiple. Note this means in the UI you can do for example `photo, cinematic ||| anime, cartoon` to compare multiple combos easily. |\n| `Seed` | Integer | `1`, `2`, `3`, ... | |\n| `Steps` | Integer | `20`, `50`, ... | |\n| `CFG Scale` | Decimal | `5`, `7.5`, `12`, ... | |\n| `Width` | Integer | `512`, `768`, ... | Initial generation width. |\n| `Height` | Integer | `512`, `768`, ... | Initial generation height. |\n| `Out Width` | Integer | `512`, `768`, ... | What resolution to save the image as (if unspecified, uses `Width`). Useful to save filespace. |\n| `Out Height` | Integer | `512`, `768`, ... | Refer to `Out Width`. |\n| `Clip Skip` | Integer | `1`, `2` | Use `2` for NAI-like models, `1` for the rest. |\n| `Var Seed` | Integer | `0`, `1`, ... | Variation seed, use with `Var Strength`. |\n| `Var Strength` | Decimal | `0`, `0.5`, ..., `1` | Variation seed strength. |\n| `Restore Faces` | Named | `true`, `false`, `GFPGan`, `CodeFormer` | Limited to the given example inputs only. |\n| `CodeFormer Weight` | Decimal | `0`, `0.5`, ..., `1` | Only applicable if `Restore Faces` is set to `CodeFormer`. |\n| `Denoising` | Decimal | `0`, `0.5`, ..., `1` | Denoising strength for img2img or HR fix. |\n| `ETA` | Decimal | `0`, `0.5`, ..., `1` | ? |\n| `ETA Noise Seed Delta` | Integer |  `0`, `31337` | use `31337` to replicate NovelAI results, use `0` for anything else. Not very useful. |\n| `Sigma Churn` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. |\n| `Sigma Tmin` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. |\n| `Sigma Tmax` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. |\n| `Sigma Noise` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. |\n| `Tiling` | Boolean | `true`, `false` | Useful for textures. |\n| `Image Mask Weight` | Decimal | `0`, `0.5`, ..., `1` | Conditional image mask weight. Only applies to img2img or HR fix. |\n| `Enable Highres Fix` | Boolean | `true`, `false` | Required for other HR settings to work. Defaults denoising strength to `0.75` if not specified. Only valid in txt2img. |\n| `Highres Scale` | Decimal | `2`, `2.5`, ..., `16` | How much to scale by for HR fix. |\n| `Highres Steps` | Integer | `20`, `50`, ... | Secondary steps for HR fix. |\n| `Highres Upscaler` | Named | `None`, `Latent`, ... | Upscaler mode to use prior to running Highres Fix. |\n| `Highres Resize Width` | Integer | `512`, `768`, ... | Resolution to target as final output size for Highres Fix, overrides `Highres Scale`. |\n| `Highres Resize Height` | Integer | `512`, `768`, ... | See `Highres Resize Width` above. |\n| `Highres Upscale To Width` | Integer | `512`, `768`, ... | Resolution to upscale to prior to running Highres Fix. |\n| `Highres Upscale To Height` | Integer | `512`, `768`, ... | See `Highres Upscale To Height` above. |\n| `Image CFG Scale` | Decimal | `5`, `7.5`, `12`, ... | Image CFG Scale, for Instruct pix2pix usage. |\n| `Use Result Index` | Integer | `0`, `1`, ... | Special trick to get a non-zero result image index, eg for ControlNet secondary output image. |\n\n- All setting names are **case insensitive and spacing insensitive**. That means `CFG scale`, `cfgscale`, `CFGSCALE`, etc. are all read as the same.\n    - Inputs where possible also similarly insensitive, including model names.\n    - Inputs have error checking at the start, to avoid the risk of it working fine until 3 hours into a very big grid run.\n- Note that it will be processed from bottom to top\n    - so if you have  first `samplers` DDIM and Euler, then `steps` 20 and 10, then `seeds` 1 and 2, it will go in this order:\n        - Sampler=DDIM, Steps=20, Seed=1\n        - Sampler=DDIM, Steps=20, Seed=**2**\n        - Sampler=DDIM, Steps=**10**, Seed=1\n        - Sampler=DDIM, Steps=10, Seed=2\n        - Sampler=**Euler**, Steps=20, Seed=1\n        - Sampler=Euler, Steps=20, Seed=2\n        - Sampler=Euler, Steps=10, Seed=1\n        - Sampler=Euler, Steps=10, Seed=2\n    - So, things that take time to load, like `Model`, should be put near the top, so they don't have to be loaded repeatedly.\n\n--------------\n\n### Supported Extensions\n\n#### Dynamic Thresholding (CFG Scale Fix)\n\nExtension docs: <https://github.com/mcmonkeyprojects/sd-dynamic-thresholding>\n\n| Name | Type | Example | Notes |\n| --- | --- | --- | ----------- |\n| `DynamicThreshold Enable` | Boolean | `true`, `false` | |\n| `DynamicThreshold Mimic Scale` | Decimal | `5`, `7.5`, `12`, ... | |\n| `DynamicThreshold Threshold Percentile` | Decimal | `0`, `0.5`, ..., `1.0` | |\n| `DynamicThreshold Mimic Mode` | Named | `Constant`, `Linear Down`, `Cosine Down`, `Half Cosine Down`, `Linear Up`, `Cosine Up`, `Half Cosine Up`, `Power Up` | |\n| `DynamicThreshold CFG Mode` | Named | `Constant`, `Linear Down`, `Cosine Down`, `Half Cosine Down`, `Linear Up`, `Cosine Up`, `Half Cosine Up`, `Power Up` | |\n| `DynamicThreshold Mimic Scale Minimum` | Decimal | `5`, `7.5`, `12`, ... | |\n| `DynamicThreshold CFG Scale Minimum` | Decimal | `5`, `7.5`, `12`, ... | |\n| `DynamicThreshold Power Value` | Decimal | `2`, `4`, ... | For `Power Up` mode only. |\n| `DynamicThreshold Scaling Startpoint` | Named | `ZERO`, `MEAN` | |\n| `DynamicThreshold Variability Measure` | Named | `STD`, `AD` | |\n| `DynamicThreshold Interpolate Phi` | Decimal | `0`, `0.5`, ..., `1.0` | |\n| `DynamicThreshold Separate Feature Channels` | Boolean | `true`, `false` | |\n\n#### ControlNet\n\nExtension docs: <https://github.com/Mikubill/sd-webui-controlnet>\n\nNote: must enable `Allow other script to control this extension` in `Settings` -> `ControlNet`\n\n| Name | Type | Example | Notes |\n| --- | --- | --- | ----------- |\n| `ControlNet Enable` | Boolean | `true`, `false` | |\n| `ControlNet Preprocessor` | Named | `none`, `canny`, `depth`, `hed`, `mlsd`, `normal_map`, `openpose`, `openpose_hand`, `pidinet`, `scribble`, `fake_scribble`, `segmentation` | |\n| `ControlNet Model` | Named | `diff_control_sd15_canny_fp16`, ... | |\n| `ControlNet Weight` | Decimal | `0.0`, `0.5`, ..., `2.0` | |\n| `ControlNet Guidance Strength` | Decimal | `0.0`, `0.5`, ..., `1.0` | |\n| `ControlNet Annotator Resolution` | Integer | `64`, `512`, ..., `2048` | |\n| `ControlNet Threshold A` | Integer | `64`, `512`, ..., `256` | |\n| `ControlNet Threshold B` | Integer | `64`, `512`, ..., `256` | |\n| `ControlNet Image` | Text | `pose.png`, `otherpose.jpg`, ... | Put image files in `(EXTENSION FOLDER)/assets/images/`, as `png`, `jpg`, or `webp`. Subfolders allowed. |\n\n#### Other Extensions\n\n- Any extension has the ability to add its own modes with the following code:\n```py\n# Verify grid extension is present\nimport importlib\nif importlib.util.find_spec(\"gridgencore\") is not None:\n    import gridgencore\n    from gridgencore import GridSettingMode\n    # p is the SD processing object, v is the value\n    def apply(p, v):\n        p.some_setting_here = v\n    # dry: bool, type: str, apply: callable, min: float = None, max: float = None, clean: callable = None\n    gridgencore.registerMode(\"mySettingNameHere\", GridSettingMode(True, \"text\", apply))\n    # for apply if the param is a 'p' field, you can use gridgencore.apply_field(\"fieldname\")\n```\n\n--------------\n\n### 2: Grid Content Generation via WebUI\n\n![img](github/webui_ref.png)\n\n- Open the WebUI\n- Go to the `txt2img` or `img2img` tab\n- At the bottom of the page, find the `Script` selection box, and select `Generate Infinite-Axis Grid`\n- Select options at will. You can hover your mouse over each option for extra usage information.\n- Select your grid definition file from earlier.\n    - If it's not there, you might just need to hit the Refresh button on the right side.\n    - If it's still not, there double check that your file is in the `assets/` folder of the extension, and that it has a proper `.yml` extension.\n- Hit your `Generate` button (the usual big orange one at the top), and wait.\n- The output folder will be named based on your `.yml` file's name.\n\n--------------\n\n### 3: Using The Output\n\n![img](github/files_ref.png)\n\n- Find the `index.html` file\n    - It's normally in `(your grid output directory)/(filename)/index.html`\n        - The example file might output to `outputs/grids/short_example/index.html`\n- Open the HTML file in a browser. Enjoy.\n- If you want to share the content, just copy/paste the whole folder into a webserver somewhere.\n    - Or upload to github and make GitHub.io pages host it for you. [See example here](https://github.com/mcmonkeyprojects/mcmonkeyprojects.github.io)\n- You have a few different clickable options:\n    - `Show descriptions of axes and values`: if you used descriptions, you can uncheck this box to hide them. Helps save space for direct viewing.\n    - `Auto-scale images to viewport width`: this is handy for a few different scenarios\n        - A: if your images are small and your screen is big, checking this option makes them bigger\n        - B: if your images are so big they're going off the edge, checking this option makes them smaller\n        - C: if checked, you can zoom in/out of the page using your browser zoom (CTRL + Mouse Wheel) to change the UI size without affecting the image size\n            - if unchecked, you can zoom in/out to change the size of the images.\n    - `Sticky navigation`: when checked, the navigation will stick to the top of the screen as you scroll down. Helps you quickly change axes while scrolling around without losing your place.\n    - `Advanced Settings`: when clicked, it will open a dropdown with more advanced settings\n        - ![img](github/advanced_settings_ref.png)\n        - `Auto cycle every (x) seconds`: you can set these to non-zero values to the grid automatically change settings over time. For example, if you set your \"Seed\" option to \"3 seconds\", then every 3 seconds the seed will change (cycling between the options you have in order). This was suggested by [itswhateverman in issue #2](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/2).\n        - `Show value`: you can uncheck any box to hide a value from the grid. Helps if you want to ignore some of the values and get a clean grid of just the ones you care about. This was suggested by [piyarsquare in issue #4](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/4).\n    - You can also click on any image to view it fullscreen and see its metadata (if included in output). While in this mode, you can use arrow keys to quick navigate between images, or press Escape to close (This suggested by [itswhateverman in issue #5](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/5) and [issue #17](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/17)).\n    - You can also set the `X Super-axis` and `Y Super-axis` to unique axes to get a grid-of-grids!\n        - ![img](github/super_axis_demo.png)\n    - You can also quicksave preview images of the grid, or even generate GIFs that autoscroll through an axis, all with a few easy buttons on the viewer page!\n\n--------------\n\n### 4: Expanding Later\n\nIf you want to add more content to a grid you already made, you can do that:\n\n- Use the same `yml` file.\n- You can add new values to an axis freely.\n- If you remove values, they will be excluded from the output but pre-existing generated images won't be removed.\n- You can add axes, but you'll have to regenerate all images if so.\n    - Probably save as a new filename in that case.\n- If you're just adding a new value, make sure to leave `overwriting existing images` off.\n\n----------------------\n\n### Credits\n\n- This design was partially inspired by the \"XYZ Plot\" script by \"xrypgame\" (not to be confused with the \"XYZ Plot\" script in Auto WebUI which is actually just the \"X/Y Plot\" script but they added a \"Z\" lol)\n- Sections of code are referenced from the WebUI itself, and its default \"X/Y Plot\" script (since renamed to labeled \"XYZ Plot\").\n- Some sections of code were referenced from various other relevant sources, for example the Dreambooth extension by d8ahazard was referenced for a JavaScript code trick (titles override).\n- Some sections of code were referenced from, well, random StackOverflow answers and a variety of other googled up documentation and answer sites. I haven't kept track of them, but I'm glad to live in a world where so many developers are happy and eager to help each other learn and grow. So, thank you to all members of the FOSS community!\n- Thanks to the authors of all [merged PRs](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/pulls?q=is%3Apr+is%3Aclosed+is%3Amerged).\n- Thanks to the authors of all issues labeled as [Completed](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues?q=label%3ACompleted).\n- Thanks to StabilityAI, RunwayML, CompVis for Stable Diffusion, and the researchers whose work was incorporated.\n- Thanks to AUTOMATIC1111 and the long list of contributors for the WebUI.\n\n----------------------\n\n### Common Issues\n\n```\n  File \"stable-diffusion-webui\\modules\\images.py\", line 508, in _atomically_save_image\n    image_format = Image.registered_extensions()[extension]\nKeyError: '.jpg'\n```\nIf you have this error, just hit generate again. I'm not sure why it happens, it just does at random sometimes on the first time the WebUI starts up. It seems to happen when you use `OutWidth`/`OutHeight` settings and is prevented by running any generation without a custom out-resolution. Might be some required initialization is getting skipped when an image is rescaled?\n\n----------------------\n\n### Licensing pre-note:\n\nThis is an open source project, provided entirely freely, for everyone to use and contribute to.\n\nIf you make any changes that could benefit the community as a whole, please contribute upstream.\n\n### The short of the license is:\n\nYou can do basically whatever you want, except you may not hold any developer liable for what you do with the software.\n\n### The long version of the license follows:\n\nThe MIT License (MIT)\n\nCopyright (c) 2022-2023 Alex \"mcmonkey\" Goodwin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "assets/a1111webui.js",
    "content": "/**\n * This file is part of Infinity Grid Generator, view the README.md at https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script for more information.\n */\n\nfunction genParamQuote(text) {\n    // Referenced to match generation_parameters_copypaste.py - quote(text)\n    if (!text.includes(',')) {\n        return text;\n    }\n    return '\"' + text.toString().replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"') + '\"';\n}\n\nfunction formatMet(name, val, bad) {\n    if (val == null) {\n        return '';\n    }\n    val = val.toString();\n    if (bad != undefined && val == bad) {\n        return '';\n    }\n    return name + ': ' + genParamQuote(val) + ', ';\n}\n\nfunction formatMetadata(valSet) {\n    var count = Object.keys(valSet).length;\n    if (count == 0) {\n        return '';\n    }\n    else if (count == 1) {\n        return valSet['error'];\n    }\n    // Referenced to match processing.py - create_infotext(p)\n    var negative = valSet['negativeprompt'];\n    if (negative.length > 0) {\n        negative = '\\nNegative prompt: ' + negative;\n    }\n    const handled = ['steps', 'sampler', 'cfgscale', 'seed', 'restorefaces', 'width', 'height', 'model', 'varseed', 'varstrength', 'denoising', 'eta', 'clipskip', 'vae', 'sigmachurn', 'sigmatmin', 'sigmatmax', 'sigmanoise', 'prompt', 'negativeprompt', 'codeformerweight'];\n    var keyData = formatMet('Steps', valSet['steps'])\n        + formatMet('Sampler', valSet['sampler'])\n        + formatMet('CFG scale', valSet['cfgscale'])\n        + formatMet('Seed', valSet['seed'])\n        + formatMet('Face restoration', valSet['restorefaces'], 'false')\n        + formatMet('Size', valSet['width'] + 'x' + valSet['height'])\n        // model hash\n        + formatMet('Model', valSet['model'])\n        // Batch size, batch pos\n        + formatMet('Variation seed', valSet['varseed'], '0')\n        + formatMet('Variation seed strength', valSet['varstrength'], '0')\n        // Seed resize from\n        + formatMet('Denoising strength', valSet['denoising'])\n        // Conditional mask weight\n        + formatMet('Eta', valSet['eta'])\n        + formatMet('Clip skip', valSet['clipskip'], '1')\n        // ENSD\n        ;\n        // Not part of normal gen-params\n    var extraData = formatMet('VAE', valSet['vae'])\n        + formatMet('Sigma Churn', valSet['sigmachurn'], '0')\n        + formatMet('Sigma T-Min', valSet['sigmatmin'], '0')\n        + formatMet('Sigma T-Max', valSet['sigmatmax'], '1')\n        + formatMet('Sigma Noise', valSet['sigmanoise'], '1')\n        + (valSet['restorefaces'] == 'CodeFormer' ? formatMet('CodeFormer Weight', valSet['codeformerweight']) : '');\n    var lastData = '';\n    for (const [key, value] of Object.entries(valSet)) {\n        if (!handled.includes(key) && value != null) {\n            lastData += `${key}: ${value}, `;\n        }\n    }\n    if (lastData.length > 2) {\n        lastData = '\\n(Other): ' + lastData.substring(0, lastData.length - 2);\n    }\n    keyData = keyData.substring(0, keyData.length - 2);\n    if (extraData.length > 2) {\n        extraData = extraData.substring(0, extraData.length - 2);\n    }\n    return valSet['prompt'] + negative + '\\n' + keyData + '\\n' + extraData + lastData;\n}\n\nfunction crunchParamHook(data, key, value) {\n    if (key == 'promptreplace') {\n        var replacers = value.split('=', 2);\n        var match = replacers[0].trim();\n        var replace = replacers[1].trim();\n        data['prompt'] = data['prompt'].replaceAll(match, replace);\n        data['negativeprompt'] = data['negativeprompt'].replaceAll(match, replace);\n        return true;\n    }\n    return false;\n}\n"
  },
  {
    "path": "assets/grid.schema.json",
    "content": "{\n    \"$schema\": \"http://json-schema.org/draft-06/schema#\",\n    \"type\": \"object\",\n    \"properties\": {\n        \"grid\": {\n            \"$ref\": \"#/definitions/Grid\"\n        },\n        \"axes\": {\n            \"$ref\": \"#/definitions/Axes\"\n        },\n        \"variables\": {\n            \"$ref\": \"#/definitions/Variables\"\n        }\n    },\n    \"required\": [\n        \"axes\",\n        \"grid\"\n    ],\n    \"title\": \"InfinityGrid\",\n    \"definitions\": {\n        \"Variables\": {\n            \"type\": \"object\",\n            \"patternProperties\": {\n                \"\\\\(.*\\\\)\": {\n                    \"oneOf\": [\n                        {\"type\": \"string\"},\n                        {\"type\": \"number\"}\n                    ]\n                }\n            }\n        },\n        \"Axes\": {\n            \"type\": \"object\",\n            \"patternProperties\": {\n                \".*\": {\n                    \"$ref\": \"#/definitions/Axis\" \n                }\n            },\n            \"title\": \"Axes\"\n        },\n        \"Axis\": {\n            \"oneOf\": [{\n                \"type\": \"string\"\n            },\n            {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"title\": {\n                        \"oneOf\": [\n                            {\"type\": \"string\"},\n                            {\"type\": \"number\"}\n                        ]\n                    },\n                    \"default\": {\n                        \"oneOf\": [{\n                                \"type\": \"string\"\n                            },\n                            {\n                                \"type\": \"number\"\n                            }\n                        ]\n                    },\n                    \"description\": {\n                        \"type\": \"string\"\n                    },\n                    \"values\": {\n                        \"patternProperties\": {\n                            \".*\": {\n                                \"$ref\": \"#/definitions/Value\"\n                            }\n                        }\n                    }\n                },\n                \"required\": [\"title\", \"values\"]\n            }]\n        },\n        \"Value\": {\n            \"oneOf\": [{\n                \"type\": \"string\",\n                \"pattern\": \"(Sampler|sampler|Model|model|VAE|vae|Prompt|prompt|NegativePrompt|negativeprompt|Negative Prompt|negative prompt|PromptReplace|promptreplace|Prompt Replace|prompt replace|Prompt Replace|prompt replace|Seed|seed|Steps|steps|CFGScale|cfgscale|CFG Scale|cfg scale|CFGscale|CFG scale|Width|width|Height|height|OutWidth|outwidth|Out Width|out width|OutHeight|outheight|Out Height|out height|ClipSkip|clipskip|Clip Skip|clip skip|VarSeed|varseed|Var Seed|var seed|VarStrength|varstrength|Var Strength|var strength|CodeFormerWeight|codeformerweight|CodeFormer Weight|codeformer weight|Denoising|denoising|ETA|eta|ETANoiseSeedDelta|etanoiseseeddelta|ETA Noise Seed Delta|eta noise seed delta|SigmaChurn|sigmachurn|Sigma Churn|sigma churn|SigmaTmin|sigmatmin|Sigma Tmin|sigma tmin|SigmaTmax|sigmatmax|Sigma Tmax|sigma tmax|SigmaNoise|sigmanoise|Sigma Noise|sigma noise|Tiling|tiling|ImageMaskWeight|imagemaskweight|Image Mask Weight|image mask weight|EnableHighresFix|enablehighresfix|Enable Highres Fix|enable highres fix|HighresScale|highresscale|Highres Scale|highres scale|HighresSteps|highressteps|Highres Steps|highres steps|HighresUpscaler|highresupscaler|Highres Upscaler|highres upscaler|HighresResizeWidth|highresresizewidth|Highres Resize Width|highres resize width|HighresResizeHeight|highresresizeheight|Highres Resize Height|highres resize height|HighresUpscaleToWidth|highresupscaletowidth|Highres Upscale To Width|highres upscale to width|HighresUpscaleToHeight|highresupscaletoheight|Highres Upscale To Height|highres upscale to height|RestoreFaces|Restore Faces|restorefaces|restore faces|([dD]ynamic\\\\s?[Tt]hreshold.*)|)\\\\=.*\"\n            },\n            {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"title\": {\n                        \"oneOf\": [\n                            {\"type\": \"string\"},\n                            {\"type\": \"number\"}\n                        ]\n                    },\n                    \"skip\": {\n                        \"type\": \"boolean\"\n                    },\n                    \"show\": {\n                        \"type\": \"boolean\"\n                    },\n                    \"description\": {\n                        \"type\": \"string\"\n                    },\n                    \"params\": {\n                        \"$ref\": \"#/definitions/GridParams\"\n                    }\n                },\n                \"required\": [\"title\", \"params\"]\n            }\n        ]\n        },\n        \"Grid\": {\n            \"type\": \"object\",\n            \"additionalProperties\": false,\n            \"properties\": {\n                \"title\": {\n                    \"type\": \"string\"\n                },\n                \"author\": {\n                    \"type\": \"string\"\n                },\n                \"description\": {\n                    \"type\": \"string\"\n                },\n                \"params\": {\n                    \"$ref\": \"#/definitions/GridParams\"\n                },\n                \"format\": {\n                    \"type\": \"string\",\n                    \"enum\": [\"png\", \"jpg\", \"webp\"]\n                }\n            },\n            \"required\": [\n                \"author\",\n                \"description\",\n                \"format\",\n                \"title\"\n            ],\n            \"title\": \"Grid\"\n        },\n        \"GridParams\": {\n            \"type\": \"object\",\n            \"additionalProperties\": false,\n            \"properties\": {\n                \"Sampler\": { \"type\": \"string\" }, \"sampler\": { \"type\": \"string\" },\n                \"Model\": { \"type\": \"string\" }, \"model\": { \"type\": \"string\" },\n                \"VAE\": { \"type\": \"string\" }, \"vae\": { \"type\": \"string\" },\n                \"Prompt\": { \"type\": \"string\" }, \"prompt\": { \"type\": \"string\" },\n                \"NegativePrompt\": { \"type\": \"string\" }, \"negativeprompt\": { \"type\": \"string\" }, \"Negative Prompt\": { \"type\": \"string\" }, \"negative prompt\": { \"type\": \"string\" },\n                \"PromptReplace\": { \"type\": \"string\" }, \"promptreplace\": { \"type\": \"string\" }, \"Prompt Replace\": { \"type\": \"string\" }, \"prompt replace\": { \"type\": \"string\" }, \"Prompt  Replace\": { \"type\": \"string\" }, \"prompt  replace\": { \"type\": \"string\" },\n                \"Seed\": { \"type\": \"integer\" }, \"seed\": { \"type\": \"integer\" },\n                \"Steps\": { \"type\": \"integer\" }, \"steps\": { \"type\": \"integer\" },\n                \"CFGScale\": { \"type\": \"number\" }, \"cfgscale\": { \"type\": \"number\" }, \"CFG Scale\": { \"type\": \"number\" }, \"cfg scale\": { \"type\": \"number\" }, \"CFGscale\": { \"type\": \"number\" }, \"CFG scale\": { \"type\": \"number\" },\n                \"Width\": { \"type\": \"integer\" }, \"width\": { \"type\": \"integer\" },\n                \"Height\": { \"type\": \"integer\" }, \"height\": { \"type\": \"integer\" },\n                \"OutWidth\": { \"type\": \"integer\" }, \"outwidth\": { \"type\": \"integer\" }, \"Out Width\": { \"type\": \"integer\" }, \"out width\": { \"type\": \"integer\" },\n                \"OutHeight\": { \"type\": \"integer\" }, \"outheight\": { \"type\": \"integer\" }, \"Out Height\": { \"type\": \"integer\" }, \"out height\": { \"type\": \"integer\" },\n                \"ClipSkip\": { \"type\": \"integer\" }, \"clipskip\": { \"type\": \"integer\" }, \"Clip Skip\": { \"type\": \"integer\" }, \"clip skip\": { \"type\": \"integer\" },\n                \"VarSeed\": { \"type\": \"integer\" }, \"varseed\": { \"type\": \"integer\" }, \"Var Seed\": { \"type\": \"integer\" }, \"var seed\": { \"type\": \"integer\" },\n                \"VarStrength\": { \"type\": \"number\" }, \"varstrength\": { \"type\": \"number\" }, \"Var Strength\": { \"type\": \"number\" }, \"var strength\": { \"type\": \"number\" },\n                \"CodeFormerWeight\": { \"type\": \"number\" }, \"codeformerweight\": { \"type\": \"number\" }, \"CodeFormer Weight\": { \"type\": \"number\" }, \"codeformer weight\": { \"type\": \"number\" },\n                \"Denoising\": { \"type\": \"number\" }, \"denoising\": { \"type\": \"number\" },\n                \"ETA\": { \"type\": \"number\" }, \"eta\": { \"type\": \"number\" },\n                \"ETANoiseSeedDelta\": { \"type\": \"integer\" }, \"etanoiseseeddelta\": { \"type\": \"integer\" }, \"ETA Noise Seed Delta\": { \"type\": \"integer\" }, \"eta noise seed delta\": { \"type\": \"integer\" },\n                \"SigmaChurn\": { \"type\": \"number\" }, \"sigmachurn\": { \"type\": \"number\" }, \"Sigma Churn\": { \"type\": \"number\" }, \"sigma churn\": { \"type\": \"number\" },\n                \"SigmaTmin\": { \"type\": \"number\" }, \"sigmatmin\": { \"type\": \"number\" }, \"Sigma Tmin\": { \"type\": \"number\" }, \"sigma tmin\": { \"type\": \"number\" },\n                \"SigmaTmax\": { \"type\": \"number\" }, \"sigmatmax\": { \"type\": \"number\" }, \"Sigma Tmax\": { \"type\": \"number\" }, \"sigma tmax\": { \"type\": \"number\" },\n                \"SigmaNoise\": { \"type\": \"number\" }, \"sigmanoise\": { \"type\": \"number\" }, \"Sigma Noise\": { \"type\": \"number\" }, \"sigma noise\": { \"type\": \"number\" },\n                \"Tiling\": { \"type\": \"boolean\" }, \"tiling\": { \"type\": \"boolean\" },\n                \"ImageMaskWeight\": { \"type\": \"number\" }, \"imagemaskweight\": { \"type\": \"number\" }, \"Image Mask Weight\": { \"type\": \"number\" }, \"image mask weight\": { \"type\": \"number\" },\n                \"EnableHighresFix\": { \"type\": \"boolean\" }, \"enablehighresfix\": { \"type\": \"boolean\" }, \"Enable Highres Fix\": { \"type\": \"boolean\" }, \"enable highres fix\": { \"type\": \"boolean\" },\n                \"HighresScale\": { \"type\": \"number\" }, \"highresscale\": { \"type\": \"number\" }, \"Highres Scale\": { \"type\": \"number\" }, \"highres scale\": { \"type\": \"number\" },\n                \"HighresSteps\": { \"type\": \"integer\" }, \"highressteps\": { \"type\": \"integer\" }, \"Highres Steps\": { \"type\": \"integer\" }, \"highres steps\": { \"type\": \"integer\" },\n                \"HighresUpscaler\": { \"type\": \"string\" }, \"highresupscaler\": { \"type\": \"string\" }, \"Highres Upscaler\": { \"type\": \"string\" }, \"highres upscaler\": { \"type\": \"string\" },\n                \"HighresResizeWidth\": { \"type\": \"integer\" }, \"highresresizewidth\": { \"type\": \"integer\" }, \"Highres Resize Width\": { \"type\": \"integer\" }, \"highres resize width\": { \"type\": \"integer\" },\n                \"HighresResizeHeight\": { \"type\": \"integer\" }, \"highresresizeheight\": { \"type\": \"integer\" }, \"Highres Resize Height\": { \"type\": \"integer\" }, \"highres resize height\": { \"type\": \"integer\" },\n                \"HighresUpscaleToWidth\": { \"type\": \"integer\" }, \"highresupscaletowidth\": { \"type\": \"integer\" }, \"Highres Upscale To Width\": { \"type\": \"integer\" }, \"highres upscale to width\": { \"type\": \"integer\" },\n                \"HighresUpscaleToHeight\": { \"type\": \"integer\" }, \"highresupscaletoheight\": { \"type\": \"integer\" }, \"Highres Upscale To Height\": { \"type\": \"integer\" }, \"highres upscale to height\": { \"type\": \"integer\" },\n                \"RestoreFaces\": { \"oneOf\": [{ \"type\" : \"boolean\"}, { \"type\": \"string\", \"enum\": [\"GFPGan\", \"CodeFormer\", \"true\", \"false\", \"gfpgan\", \"codeformer\"] }]},\n                \"Restore Faces\": { \"oneOf\": [{ \"type\" : \"boolean\"}, { \"type\": \"string\", \"enum\": [\"GFPGan\", \"CodeFormer\", \"true\", \"false\", \"gfpgan\", \"codeformer\"] }]},\n                \"restorefaces\": { \"oneOf\": [{ \"type\" : \"boolean\"}, { \"type\": \"string\", \"enum\": [\"GFPGan\", \"CodeFormer\", \"true\", \"false\", \"gfpgan\", \"codeformer\"] }]},\n                \"restore faces\": { \"oneOf\": [{ \"type\" : \"boolean\"}, { \"type\": \"string\", \"enum\": [\"GFPGan\", \"CodeFormer\", \"true\", \"false\", \"gfpgan\", \"codeformer\"] }]}\n            },\n            \"title\": \"GridParams\"\n        }\n    }\n}\n"
  },
  {
    "path": "assets/images/put-usable-images-here.txt",
    "content": ""
  },
  {
    "path": "assets/jsgif.js",
    "content": "/**\n * This class lets you encode animated GIF files\n * Base class :  http://www.java2s.com/Code/Java/2D-Graphics-GUI/AnimatedGifEncoder.htm\n * @author Kevin Weiner (original Java version - kweiner@fmsware.com)\n * @author Thibault Imbert (AS3 version - bytearray.org)\n * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif)\n * @version 0.1 AS3 implementation\n */\n\nGIFEncoder = function() {\n\n\tfor (var i = 0, chr = {}; i < 256; i++)\n\t\tchr[i] = String.fromCharCode(i);\n\n\tfunction ByteArray() {\n\t\tthis.bin = [];\n\t}\n\n\tByteArray.prototype.getData = function() {\n\t\tfor (var v = '', l = this.bin.length, i = 0; i < l; i++)\n\t\t\tv += chr[this.bin[i]];\n\t\treturn v;\n\t};\n\n\tByteArray.prototype.writeByte = function(val) {\n\t\tthis.bin.push(val);\n\t};\n\n\tByteArray.prototype.writeUTFBytes = function(string) {\n\t\tfor (var l = string.length, i = 0; i < l; i++)\n\t\t\tthis.writeByte(string.charCodeAt(i));\n\t};\n\n\tByteArray.prototype.writeBytes = function(array, offset, length) {\n\t\tfor (var l = length || array.length, i = offset || 0; i < l; i++)\n\t\t\tthis.writeByte(array[i]);\n\t};\n\n\tvar exports = {};\n\tvar width; // image size\n\tvar height;\n\tvar transparent = null; // transparent color if given\n\tvar transIndex; // transparent index in color table\n\tvar repeat = -1; // no repeat\n\tvar delay = 0; // frame delay (hundredths)\n\tvar started = false; // ready to output frames\n\tvar out;\n\tvar image; // current frame\n\tvar pixels; // BGR byte array from frame\n\tvar indexedPixels; // converted frame indexed to palette\n\tvar colorDepth; // number of bit planes\n\tvar colorTab; // RGB palette\n\tvar usedEntry = []; // active palette entries\n\tvar palSize = 7; // color table size (bits-1)\n\tvar dispose = -1; // disposal code (-1 = use default)\n\tvar closeStream = false; // close stream when finished\n\tvar firstFrame = true;\n\tvar sizeSet = false; // if false, get size from first frame\n\tvar sample = 10; // default sample interval for quantizer\n\tvar comment = \"Generated by jsgif (https://github.com/antimatter15/jsgif/)\"; // default comment for generated gif\n\n\t/**\n\t * Sets the delay time between each frame, or changes it for subsequent frames\n\t * (applies to last frame added)\n\t * int delay time in milliseconds\n\t * @param ms\n\t */\n\n\tvar setDelay = exports.setDelay = function setDelay(ms) {\n\t\tdelay = Math.round(ms / 10);\n\t};\n\n\t/**\n\t * Sets the GIF frame disposal code for the last added frame and any\n\t *\n\t * subsequent frames. Default is 0 if no transparent color has been set,\n\t * otherwise 2.\n\t * @param code\n\t * int disposal code.\n\t */\n\n\tvar setDispose = exports.setDispose = function setDispose(code) {\n\t\tif (code >= 0) dispose = code;\n\t};\n\n\t/**\n\t * Sets the number of times the set of GIF frames should be played. Default is\n\t * 1; 0 means play indefinitely. Must be invoked before the first image is\n\t * added.\n\t *\n\t * @param iter\n\t * int number of iterations.\n\t * @return\n\t */\n\n\tvar setRepeat = exports.setRepeat = function setRepeat(iter) {\n\t\tif (iter >= 0) repeat = iter;\n\t};\n\n\t/**\n\t * Sets the transparent color for the last added frame and any subsequent\n\t * frames. Since all colors are subject to modification in the quantization\n\t * process, the color in the final palette for each frame closest to the given\n\t * color becomes the transparent color for that frame. May be set to null to\n\t * indicate no transparent color.\n\t * @param\n\t * Color to be treated as transparent on display.\n\t */\n\n\tvar setTransparent = exports.setTransparent = function setTransparent(c) {\n\t\ttransparent = c;\n\t};\n\n\n\t/**\n\t * Sets the comment for the block comment\n\t * @param\n\t * string to be insterted as comment\n\t */\n\n\tvar setComment = exports.setComment = function setComment(c) {\n\t\tcomment = c;\n\t};\n\n\n\n\t/**\n\t * The addFrame method takes an incoming BitmapData object to create each frames\n\t * @param\n\t * BitmapData object to be treated as a GIF's frame\n\t */\n\n\tvar addFrame = exports.addFrame = function addFrame(im, is_imageData) {\n\n\t\tif ((im === null) || !started || out === null) {\n\t\t\tthrow new Error(\"Please call start method before calling addFrame\");\n\t\t}\n\n\t\tvar ok = true;\n\n\t\ttry {\n\t\t\tif (!is_imageData) {\n\t\t\t\timage = im.getImageData(0, 0, im.canvas.width, im.canvas.height).data;\n\t\t\t\tif (!sizeSet) setSize(im.canvas.width, im.canvas.height);\n\t\t\t} else {\n\t\t\t\tif(im instanceof ImageData) {\n\t\t\t\t\timage = im.data;\n\t\t\t\t\tif(!sizeset || width!=im.width || height!=im.height) {\n\t\t\t\t\t\tsetSize(im.width,im.height);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t} else if(im instanceof Uint8ClampedArray) {\n\t\t\t\t\tif(im.length==(width*height*4)) {\n\t\t\t\t\t\timage=im;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(\"Please set the correct size: ImageData length mismatch\");\n\t\t\t\t\t\tok=false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"Please provide correct input\");\n\t\t\t\t\tok=false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgetImagePixels(); // convert to correct format if necessary\n\t\t\tanalyzePixels(); // build color table & map pixels\n\n\t\t\tif (firstFrame) {\n\t\t\t\twriteLSD(); // logical screen descriptior\n\t\t\t\twritePalette(); // global color table\n\t\t\t\tif (repeat >= 0) {\n\t\t\t\t\t// use NS app extension to indicate reps\n\t\t\t\t\twriteNetscapeExt();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twriteGraphicCtrlExt(); // write graphic control extension\n\t\t\tif (comment !== '') {\n\t\t\t\twriteCommentExt(); // write comment extension\n\t\t\t}\n\t\t\twriteImageDesc(); // image descriptor\n\t\t\tif (!firstFrame) writePalette(); // local color table\n\t\t\twritePixels(); // encode and write pixel data\n\t\t\tfirstFrame = false;\n\t\t} catch (e) {\n\t\t\tok = false;\n\t\t}\n\n\t\treturn ok;\n\t};\n\t\n\t/**\n\t* @description: Downloads the encoded gif with the given name\n\t* No need of any conversion from the stream data (out) to base64\n\t* Solves the issue of large file sizes when there are more frames\n\t* and does not involve in creation of any temporary data in the process\n\t* so no wastage of memory, and speeds up the process of downloading\n\t* to just calling this function.\n\t* @parameter {String} filename filename used for downloading the gif\n\t*/\n\t\n\tvar download = exports.download = function download(filename) {\n\t\tif(out===null || closeStream==false) {\n\t\t\tconsole.log(\"Please call start method and add frames and call finish method before calling download\"); \n\t\t} else {\n\t\t\tfilename= filename !== undefined ? ( filename.endsWith(\".gif\")? filename: filename+\".gif\" ): \"download.gif\";\n\t\t\tvar templink = document.createElement(\"a\");\n\t\t\ttemplink.download=filename;\n\t\t\ttemplink.href= URL.createObjectURL(new Blob([new Uint8Array(out.bin)], {type : \"image/gif\" } ));\n\t\t\ttemplink.click();\n\t\t}\n\t}\n\n\t/**\n\t * Adds final trailer to the GIF stream, if you don't call the finish method\n\t * the GIF stream will not be valid.\n\t */\n\n\tvar finish = exports.finish = function finish() {\n\n\t\tif (!started) return false;\n\n\t\tvar ok = true;\n\t\tstarted = false;\n\n\t\ttry {\n\t\t\tout.writeByte(0x3b); // gif trailer\n\t\t\tcloseStream=true;\n\t\t} catch (e) {\n\t\t\tok = false;\n\t\t}\n\n\t\treturn ok;\n\t};\n\n\t/**\n\t * Resets some members so that a new stream can be started.\n\t * This method is actually called by the start method\n\t */\n\n\tvar reset = function reset() {\n\n\t\t// reset for subsequent use\n\t\ttransIndex = 0;\n\t\timage = null;\n\t\tpixels = null;\n\t\tindexedPixels = null;\n\t\tcolorTab = null;\n\t\tcloseStream = false;\n\t\tfirstFrame = true;\n\t};\n\n\t/**\n\t * * Sets frame rate in frames per second. Equivalent to\n\t * <code>setDelay(1000/fps)</code>.\n\t * @param fps\n\t * float frame rate (frames per second)\n\t */\n\n\tvar setFrameRate = exports.setFrameRate = function setFrameRate(fps) {\n\t\tif (fps != 0xf) delay = Math.round(100 / fps);\n\t};\n\n\t/**\n\t * Sets quality of color quantization (conversion of images to the maximum 256\n\t * colors allowed by the GIF specification). Lower values (minimum = 1)\n\t * produce better colors, but slow processing significantly. 10 is the\n\t * default, and produces good color mapping at reasonable speeds. Values\n\t * greater than 20 do not yield significant improvements in speed.\n\t * @param quality\n\t * int greater than 0.\n\t * @return\n\t */\n\n\tvar setQuality = exports.setQuality = function setQuality(quality) {\n\t\tif (quality < 1) quality = 1;\n\t\tsample = quality;\n\t};\n\n\t/**\n\t * Sets the GIF frame size. The default size is the size of the first frame\n\t * added if this method is not invoked.\n\t * @param w\n\t * int frame width.\n\t * @param h\n\t * int frame width.\n\t */\n\n\tvar setSize = exports.setSize = function setSize(w, h) {\n\n\t\tif (started && !firstFrame) return;\n\t\twidth = w;\n\t\theight = h;\n\t\tif (width < 1) width = 320;\n\t\tif (height < 1) height = 240;\n\t\tsizeSet = true;\n\t};\n\n\t/**\n\t * Initiates GIF file creation on the given stream.\n\t * @param os\n\t * OutputStream on which GIF images are written.\n\t * @return false if initial write failed.\n\t */\n\n\tvar start = exports.start = function start() {\n\n\t\treset();\n\t\tvar ok = true;\n\t\tcloseStream = false;\n\t\tout = new ByteArray();\n\t\ttry {\n\t\t\tout.writeUTFBytes(\"GIF89a\"); // header\n\t\t} catch (e) {\n\t\t\tok = false;\n\t\t}\n\n\t\treturn started = ok;\n\t};\n\n\tvar cont = exports.cont = function cont() {\n\n\t\treset();\n\t\tvar ok = true;\n\t\tcloseStream = false;\n\t\tout = new ByteArray();\n\n\t\treturn started = ok;\n\t};\n\n\t/**\n\t * Analyzes image colors and creates color map.\n\t */\n\n\tvar analyzePixels = function analyzePixels() {\n\n\t\tvar len = pixels.length;\n\t\tvar nPix = len / 3;\n\t\tindexedPixels = [];\n\t\tvar nq = new NeuQuant(pixels, len, sample);\n\n\t\t// initialize quantizer\n\t\tcolorTab = nq.process(); // create reduced palette\n\n\t\t// map image pixels to new palette\n\t\tvar k = 0;\n\t\tfor (var j = 0; j < nPix; j++) {\n\t\t\tvar index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff);\n\t\t\tusedEntry[index] = true;\n\t\t\tindexedPixels[j] = index;\n\t\t}\n\n\t\tpixels = null;\n\t\tcolorDepth = 8;\n\t\tpalSize = 7;\n\n\t\t// get closest match to transparent color if specified\n\t\tif (transparent !== null) {\n\t\t\ttransIndex = findClosest(transparent);\n\t\t}\n\t};\n\n\t/**\n\t * Returns index of palette color closest to c\n\t */\n\n\tvar findClosest = function findClosest(c) {\n\n\t\tif (colorTab === null) return -1;\n\t\tvar r = (c & 0xFF0000) >> 16;\n\t\tvar g = (c & 0x00FF00) >> 8;\n\t\tvar b = (c & 0x0000FF);\n\t\tvar minpos = 0;\n\t\tvar dmin = 256 * 256 * 256;\n\t\tvar len = colorTab.length;\n\n\t\tfor (var i = 0; i < len;) {\n\t\t\tvar dr = r - (colorTab[i++] & 0xff);\n\t\t\tvar dg = g - (colorTab[i++] & 0xff);\n\t\t\tvar db = b - (colorTab[i] & 0xff);\n\t\t\tvar d = dr * dr + dg * dg + db * db;\n\t\t\tvar index = i / 3;\n\t\t\tif (usedEntry[index] && (d < dmin)) {\n\t\t\t\tdmin = d;\n\t\t\t\tminpos = index;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\treturn minpos;\n\t};\n\n\t/**\n\t * Extracts image pixels into byte array \"pixels\n\t */\n\n\tvar getImagePixels = function getImagePixels() {\n\t\tvar w = width;\n\t\tvar h = height;\n\t\tpixels = [];\n\t\tvar data = image;\n\t\tvar count = 0;\n\n\t\tfor (var i = 0; i < h; i++) {\n\n\t\t\tfor (var j = 0; j < w; j++) {\n\n\t\t\t\tvar b = (i * w * 4) + j * 4;\n\t\t\t\tpixels[count++] = data[b];\n\t\t\t\tpixels[count++] = data[b + 1];\n\t\t\t\tpixels[count++] = data[b + 2];\n\n\t\t\t}\n\n\t\t}\n\t};\n\n\t/**\n\t * Writes Graphic Control Extension\n\t */\n\n\tvar writeGraphicCtrlExt = function writeGraphicCtrlExt() {\n\t\tout.writeByte(0x21); // extension introducer\n\t\tout.writeByte(0xf9); // GCE label\n\t\tout.writeByte(4); // data block size\n\t\tvar transp;\n\t\tvar disp;\n\t\tif (transparent === null) {\n\t\t\ttransp = 0;\n\t\t\tdisp = 0; // dispose = no action\n\t\t} else {\n\t\t\ttransp = 1;\n\t\t\tdisp = 2; // force clear if using transparent color\n\t\t}\n\t\tif (dispose >= 0) {\n\t\t\tdisp = dispose & 7; // user override\n\t\t}\n\t\tdisp <<= 2;\n\t\t// packed fields\n\t\tout.writeByte(0 | // 1:3 reserved\n\t\t\tdisp | // 4:6 disposal\n\t\t\t0 | // 7 user input - 0 = none\n\t\t\ttransp); // 8 transparency flag\n\n\t\tWriteShort(delay); // delay x 1/100 sec\n\t\tout.writeByte(transIndex); // transparent color index\n\t\tout.writeByte(0); // block terminator\n\t};\n\n\t/**\n\t * Writes Comment Extention\n\t */\n\n\tvar writeCommentExt = function writeCommentExt() {\n\t\tout.writeByte(0x21); // extension introducer\n\t\tout.writeByte(0xfe); // comment label\n\t\tout.writeByte(comment.length); // Block Size (s)\n\t\tout.writeUTFBytes(comment);\n\t\tout.writeByte(0); // block terminator\n\t};\n\n\n\t/**\n\t * Writes Image Descriptor\n\t */\n\n\tvar writeImageDesc = function writeImageDesc() {\n\n\t\tout.writeByte(0x2c); // image separator\n\t\tWriteShort(0); // image position x,y = 0,0\n\t\tWriteShort(0);\n\t\tWriteShort(width); // image size\n\t\tWriteShort(height);\n\n\t\t// packed fields\n\t\tif (firstFrame) {\n\t\t\t// no LCT - GCT is used for first (or only) frame\n\t\t\tout.writeByte(0);\n\t\t} else {\n\t\t\t// specify normal LCT\n\t\t\tout.writeByte(0x80 | // 1 local color table 1=yes\n\t\t\t\t0 | // 2 interlace - 0=no\n\t\t\t\t0 | // 3 sorted - 0=no\n\t\t\t\t0 | // 4-5 reserved\n\t\t\t\tpalSize); // 6-8 size of color table\n\t\t}\n\t};\n\n\t/**\n\t * Writes Logical Screen Descriptor\n\t */\n\n\tvar writeLSD = function writeLSD() {\n\n\t\t// logical screen size\n\t\tWriteShort(width);\n\t\tWriteShort(height);\n\t\t// packed fields\n\t\tout.writeByte((0x80 | // 1 : global color table flag = 1 (gct used)\n\t\t\t0x70 | // 2-4 : color resolution = 7\n\t\t\t0x00 | // 5 : gct sort flag = 0\n\t\t\tpalSize)); // 6-8 : gct size\n\n\t\tout.writeByte(0); // background color index\n\t\tout.writeByte(0); // pixel aspect ratio - assume 1:1\n\t};\n\n\t/**\n\t * Writes Netscape application extension to define repeat count.\n\t */\n\n\tvar writeNetscapeExt = function writeNetscapeExt() {\n\t\tout.writeByte(0x21); // extension introducer\n\t\tout.writeByte(0xff); // app extension label\n\t\tout.writeByte(11); // block size\n\t\tout.writeUTFBytes(\"NETSCAPE\" + \"2.0\"); // app id + auth code\n\t\tout.writeByte(3); // sub-block size\n\t\tout.writeByte(1); // loop sub-block id\n\t\tWriteShort(repeat); // loop count (extra iterations, 0=repeat forever)\n\t\tout.writeByte(0); // block terminator\n\t};\n\n\t/**\n\t * Writes color table\n\t */\n\n\tvar writePalette = function writePalette() {\n\t\tout.writeBytes(colorTab);\n\t\tvar n = (3 * 256) - colorTab.length;\n\t\tfor (var i = 0; i < n; i++) out.writeByte(0);\n\t};\n\n\tvar WriteShort = function WriteShort(pValue) {\n\t\tout.writeByte(pValue & 0xFF);\n\t\tout.writeByte((pValue >> 8) & 0xFF);\n\t};\n\n\t/**\n\t * Encodes and writes pixel data\n\t */\n\n\tvar writePixels = function writePixels() {\n\t\tvar myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth);\n\t\tmyencoder.encode(out);\n\t};\n\n\t/**\n\t * Retrieves the GIF stream\n\t */\n\n\tvar stream = exports.stream = function stream() {\n\t\treturn out;\n\t};\n\n\tvar setProperties = exports.setProperties = function setProperties(has_start, is_first) {\n\t\tstarted = has_start;\n\t\tfirstFrame = is_first;\n\t};\n\n\treturn exports;\n\n};\n/**\n * This class handles LZW encoding\n * Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.\n * @author Kevin Weiner (original Java version - kweiner@fmsware.com)\n * @author Thibault Imbert (AS3 version - bytearray.org)\n * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif)\n * @version 0.1 AS3 implementation\n */\n\nLZWEncoder = function() {\n\n\tvar exports = {};\n\tvar EOF = -1;\n\tvar imgW;\n\tvar imgH;\n\tvar pixAry;\n\tvar initCodeSize;\n\tvar remaining;\n\tvar curPixel;\n\n\t// GIFCOMPR.C - GIF Image compression routines\n\t// Lempel-Ziv compression based on 'compress'. GIF modifications by\n\t// David Rowley (mgardi@watdcsu.waterloo.edu)\n\t// General DEFINEs\n\n\tvar BITS = 12;\n\tvar HSIZE = 5003; // 80% occupancy\n\n\t// GIF Image compression - modified 'compress'\n\t// Based on: compress.c - File compression ala IEEE Computer, June 1984.\n\t// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)\n\t// Jim McKie (decvax!mcvax!jim)\n\t// Steve Davies (decvax!vax135!petsd!peora!srd)\n\t// Ken Turkowski (decvax!decwrl!turtlevax!ken)\n\t// James A. Woods (decvax!ihnp4!ames!jaw)\n\t// Joe Orost (decvax!vax135!petsd!joe)\n\n\tvar n_bits; // number of bits/code\n\tvar maxbits = BITS; // user settable max # bits/code\n\tvar maxcode; // maximum code, given n_bits\n\tvar maxmaxcode = 1 << BITS; // should NEVER generate this code\n\tvar htab = [];\n\tvar codetab = [];\n\tvar hsize = HSIZE; // for dynamic table sizing\n\tvar free_ent = 0; // first unused entry\n\n\t// block compression parameters -- after all codes are used up,\n\t// and compression rate changes, start over.\n\n\tvar clear_flg = false;\n\n\t// Algorithm: use open addressing double hashing (no chaining) on the\n\t// prefix code / next character combination. We do a variant of Knuth's\n\t// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime\n\t// secondary probe. Here, the modular division first probe is gives way\n\t// to a faster exclusive-or manipulation. Also do block compression with\n\t// an adaptive reset, whereby the code table is cleared when the compression\n\t// ratio decreases, but after the table fills. The variable-length output\n\t// codes are re-sized at this point, and a special CLEAR code is generated\n\t// for the decompressor. Late addition: construct the table according to\n\t// file size for noticeable speed improvement on small files. Please direct\n\t// questions about this implementation to ames!jaw.\n\n\tvar g_init_bits;\n\tvar ClearCode;\n\tvar EOFCode;\n\n\t// output\n\t// Output the given code.\n\t// Inputs:\n\t// code: A n_bits-bit integer. If == -1, then EOF. This assumes\n\t// that n_bits =< wordsize - 1.\n\t// Outputs:\n\t// Outputs code to the file.\n\t// Assumptions:\n\t// Chars are 8 bits long.\n\t// Algorithm:\n\t// Maintain a BITS character long buffer (so that 8 codes will\n\t// fit in it exactly). Use the VAX insv instruction to insert each\n\t// code in turn. When the buffer fills up empty it and start over.\n\n\tvar cur_accum = 0;\n\tvar cur_bits = 0;\n\tvar masks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];\n\n\t// Number of characters so far in this 'packet'\n\tvar a_count;\n\n\t// Define the storage for the packet accumulator\n\tvar accum = [];\n\n\tvar LZWEncoder = exports.LZWEncoder = function LZWEncoder(width, height, pixels, color_depth) {\n\t\timgW = width;\n\t\timgH = height;\n\t\tpixAry = pixels;\n\t\tinitCodeSize = Math.max(2, color_depth);\n\t};\n\n\t// Add a character to the end of the current packet, and if it is 254\n\t// characters, flush the packet to disk.\n\tvar char_out = function char_out(c, outs) {\n\t\taccum[a_count++] = c;\n\t\tif (a_count >= 254) flush_char(outs);\n\t};\n\n\t// Clear out the hash table\n\t// table clear for block compress\n\n\tvar cl_block = function cl_block(outs) {\n\t\tcl_hash(hsize);\n\t\tfree_ent = ClearCode + 2;\n\t\tclear_flg = true;\n\t\toutput(ClearCode, outs);\n\t};\n\n\t// reset code table\n\tvar cl_hash = function cl_hash(hsize) {\n\t\tfor (var i = 0; i < hsize; ++i) htab[i] = -1;\n\t};\n\n\tvar compress = exports.compress = function compress(init_bits, outs) {\n\n\t\tvar fcode;\n\t\tvar i; /* = 0 */\n\t\tvar c;\n\t\tvar ent;\n\t\tvar disp;\n\t\tvar hsize_reg;\n\t\tvar hshift;\n\n\t\t// Set up the globals: g_init_bits - initial number of bits\n\t\tg_init_bits = init_bits;\n\n\t\t// Set up the necessary values\n\t\tclear_flg = false;\n\t\tn_bits = g_init_bits;\n\t\tmaxcode = MAXCODE(n_bits);\n\n\t\tClearCode = 1 << (init_bits - 1);\n\t\tEOFCode = ClearCode + 1;\n\t\tfree_ent = ClearCode + 2;\n\n\t\ta_count = 0; // clear packet\n\n\t\tent = nextPixel();\n\n\t\thshift = 0;\n\t\tfor (fcode = hsize; fcode < 65536; fcode *= 2)\n\t\t\t++hshift;\n\t\thshift = 8 - hshift; // set hash code range bound\n\n\t\thsize_reg = hsize;\n\t\tcl_hash(hsize_reg); // clear hash table\n\n\t\toutput(ClearCode, outs);\n\n\t\touter_loop: while ((c = nextPixel()) != EOF) {\n\t\t\tfcode = (c << maxbits) + ent;\n\t\t\ti = (c << hshift) ^ ent; // xor hashing\n\n\t\t\tif (htab[i] == fcode) {\n\t\t\t\tent = codetab[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\telse if (htab[i] >= 0) { // non-empty slot\n\n\t\t\t\tdisp = hsize_reg - i; // secondary hash (after G. Knott)\n\t\t\t\tif (i === 0) disp = 1;\n\n\t\t\t\tdo {\n\t\t\t\t\tif ((i -= disp) < 0)\n\t\t\t\t\t\ti += hsize_reg;\n\n\t\t\t\t\tif (htab[i] == fcode) {\n\t\t\t\t\t\tent = codetab[i];\n\t\t\t\t\t\tcontinue outer_loop;\n\t\t\t\t\t}\n\t\t\t\t} while (htab[i] >= 0);\n\t\t\t}\n\n\t\t\toutput(ent, outs);\n\t\t\tent = c;\n\t\t\tif (free_ent < maxmaxcode) {\n\t\t\t\tcodetab[i] = free_ent++; // code -> hashtable\n\t\t\t\thtab[i] = fcode;\n\t\t\t}\n\t\t\telse cl_block(outs);\n\t\t}\n\n\t\t// Put out the final code.\n\t\toutput(ent, outs);\n\t\toutput(EOFCode, outs);\n\t};\n\n\t// ----------------------------------------------------------------------------\n\tvar encode = exports.encode = function encode(os) {\n\t\tos.writeByte(initCodeSize); // write \"initial code size\" byte\n\t\tremaining = imgW * imgH; // reset navigation variables\n\t\tcurPixel = 0;\n\t\tcompress(initCodeSize + 1, os); // compress and write the pixel data\n\t\tos.writeByte(0); // write block terminator\n\t};\n\n\t// Flush the packet to disk, and reset the accumulator\n\tvar flush_char = function flush_char(outs) {\n\t\tif (a_count > 0) {\n\t\t\touts.writeByte(a_count);\n\t\t\touts.writeBytes(accum, 0, a_count);\n\t\t\ta_count = 0;\n\t\t}\n\t};\n\n\tvar MAXCODE = function MAXCODE(n_bits) {\n\t\treturn (1 << n_bits) - 1;\n\t};\n\n\t// ----------------------------------------------------------------------------\n\t// Return the next pixel from the image\n\t// ----------------------------------------------------------------------------\n\n\tvar nextPixel = function nextPixel() {\n\t\tif (remaining === 0) return EOF;\n\t\t--remaining;\n\t\tvar pix = pixAry[curPixel++];\n\t\treturn pix & 0xff;\n\t};\n\n\tvar output = function output(code, outs) {\n\n\t\tcur_accum &= masks[cur_bits];\n\n\t\tif (cur_bits > 0) cur_accum |= (code << cur_bits);\n\t\telse cur_accum = code;\n\n\t\tcur_bits += n_bits;\n\n\t\twhile (cur_bits >= 8) {\n\t\t\tchar_out((cur_accum & 0xff), outs);\n\t\t\tcur_accum >>= 8;\n\t\t\tcur_bits -= 8;\n\t\t}\n\n\t\t// If the next entry is going to be too big for the code size,\n\t\t// then increase it, if possible.\n\n\t\tif (free_ent > maxcode || clear_flg) {\n\n\t\t\tif (clear_flg) {\n\n\t\t\t\tmaxcode = MAXCODE(n_bits = g_init_bits);\n\t\t\t\tclear_flg = false;\n\n\t\t\t} else {\n\n\t\t\t\t++n_bits;\n\t\t\t\tif (n_bits == maxbits) maxcode = maxmaxcode;\n\t\t\t\telse maxcode = MAXCODE(n_bits);\n\t\t\t}\n\t\t}\n\n\t\tif (code == EOFCode) {\n\n\t\t\t// At EOF, write the rest of the buffer.\n\t\t\twhile (cur_bits > 0) {\n\t\t\t\tchar_out((cur_accum & 0xff), outs);\n\t\t\t\tcur_accum >>= 8;\n\t\t\t\tcur_bits -= 8;\n\t\t\t}\n\n\t\t\tflush_char(outs);\n\t\t}\n\t};\n\n\tLZWEncoder.apply(this, arguments);\n\treturn exports;\n};\n/*\n * NeuQuant Neural-Net Quantization Algorithm\n * ------------------------------------------\n *\n * Copyright (c) 1994 Anthony Dekker\n *\n * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See\n * \"Kohonen neural networks for optimal colour quantization\" in \"Network:\n * Computation in Neural Systems\" Vol. 5 (1994) pp 351-367. for a discussion of\n * the algorithm.\n *\n * Any party obtaining a copy of these files from the author, directly or\n * indirectly, is granted, free of charge, a full and unrestricted irrevocable,\n * world-wide, paid up, royalty-free, nonexclusive right and license to deal in\n * this software and documentation files (the \"Software\"), including without\n * limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and/or sell copies of the Software, and to permit persons who\n * receive copies from any such party to do so, with the only requirement being\n * that this copyright notice remain intact.\n */\n\n/*\n * This class handles Neural-Net quantization algorithm\n * @author Kevin Weiner (original Java version - kweiner@fmsware.com)\n * @author Thibault Imbert (AS3 version - bytearray.org)\n * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif)\n * @version 0.1 AS3 implementation\n */\n\nNeuQuant = function() {\n\n\tvar exports = {};\n\tvar netsize = 256; /* number of colours used */\n\n\t/* four primes near 500 - assume no image has a length so large */\n\t/* that it is divisible by all four primes */\n\n\tvar prime1 = 499;\n\tvar prime2 = 491;\n\tvar prime3 = 487;\n\tvar prime4 = 503;\n\tvar minpicturebytes = (3 * prime4); /* minimum size for input image */\n\n\t/*\n\t * Program Skeleton ---------------- [select samplefac in range 1..30] [read\n\t * image from input file] pic = (unsigned char*) malloc(3*width*height);\n\t * initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output\n\t * image header, using writecolourmap(f)] inxbuild(); write output image using\n\t * inxsearch(b,g,r)\n\t */\n\n\t/*\n\t * Network Definitions -------------------\n\t */\n\n\tvar maxnetpos = (netsize - 1);\n\tvar netbiasshift = 4; /* bias for colour values */\n\tvar ncycles = 100; /* no. of learning cycles */\n\n\t/* defs for freq and bias */\n\tvar intbiasshift = 16; /* bias for fractions */\n\tvar intbias = (1 << intbiasshift);\n\tvar gammashift = 10; /* gamma = 1024 */\n\tvar gamma = (1 << gammashift);\n\tvar betashift = 10;\n\tvar beta = (intbias >> betashift); /* beta = 1/1024 */\n\tvar betagamma = (intbias << (gammashift - betashift));\n\n\t/* defs for decreasing radius factor */\n\tvar initrad = (netsize >> 3); /* for 256 cols, radius starts */\n\tvar radiusbiasshift = 6; /* at 32.0 biased by 6 bits */\n\tvar radiusbias = (1 << radiusbiasshift);\n\tvar initradius = (initrad * radiusbias); /* and decreases by a */\n\tvar radiusdec = 30; /* factor of 1/30 each cycle */\n\n\t/* defs for decreasing alpha factor */\n\tvar alphabiasshift = 10; /* alpha starts at 1.0 */\n\tvar initalpha = (1 << alphabiasshift);\n\tvar alphadec; /* biased by 10 bits */\n\n\t/* radbias and alpharadbias used for radpower calculation */\n\tvar radbiasshift = 8;\n\tvar radbias = (1 << radbiasshift);\n\tvar alpharadbshift = (alphabiasshift + radbiasshift);\n\tvar alpharadbias = (1 << alpharadbshift);\n\n\t/*\n\t * Types and Global Variables --------------------------\n\t */\n\n\tvar thepicture; /* the input image itself */\n\tvar lengthcount; /* lengthcount = H*W*3 */\n\tvar samplefac; /* sampling factor 1..30 */\n\n\t// typedef int pixel[4]; /* BGRc */\n\tvar network; /* the network itself - [netsize][4] */\n\tvar netindex = [];\n\n\t/* for network lookup - really 256 */\n\tvar bias = [];\n\n\t/* bias and freq arrays for learning */\n\tvar freq = [];\n\tvar radpower = [];\n\n\tvar NeuQuant = exports.NeuQuant = function NeuQuant(thepic, len, sample) {\n\n\t\tvar i;\n\t\tvar p;\n\n\t\tthepicture = thepic;\n\t\tlengthcount = len;\n\t\tsamplefac = sample;\n\n\t\tnetwork = new Array(netsize);\n\n\t\tfor (i = 0; i < netsize; i++) {\n\n\t\t\tnetwork[i] = new Array(4);\n\t\t\tp = network[i];\n\t\t\tp[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize;\n\t\t\tfreq[i] = intbias / netsize; /* 1/netsize */\n\t\t\tbias[i] = 0;\n\t\t}\n\t};\n\n\tvar colorMap = function colorMap() {\n\n\t\tvar map = [];\n\t\tvar index = new Array(netsize);\n\n\t\tfor (var i = 0; i < netsize; i++)\n\t\t\tindex[network[i][3]] = i;\n\n\t\tvar k = 0;\n\t\tfor (var l = 0; l < netsize; l++) {\n\t\t\tvar j = index[l];\n\t\t\tmap[k++] = (network[j][0]);\n\t\t\tmap[k++] = (network[j][1]);\n\t\t\tmap[k++] = (network[j][2]);\n\t\t}\n\n\t\treturn map;\n\t};\n\n\t/*\n\t * Insertion sort of network and building of netindex[0..255] (to do after\n\t * unbias)\n\t * -------------------------------------------------------------------------------\n\t */\n\n\tvar inxbuild = function inxbuild() {\n\n\t\tvar i;\n\t\tvar j;\n\t\tvar smallpos;\n\t\tvar smallval;\n\t\tvar p;\n\t\tvar q;\n\t\tvar previouscol;\n\t\tvar startpos;\n\n\t\tpreviouscol = 0;\n\t\tstartpos = 0;\n\t\tfor (i = 0; i < netsize; i++) {\n\n\t\t\tp = network[i];\n\t\t\tsmallpos = i;\n\t\t\tsmallval = p[1]; /* index on g */\n\n\t\t\t/* find smallest in i..netsize-1 */\n\t\t\tfor (j = i + 1; j < netsize; j++) {\n\n\t\t\t\tq = network[j];\n\t\t\t\tif (q[1] < smallval) { /* index on g */\n\t\t\t\t\tsmallpos = j;\n\t\t\t\t\tsmallval = q[1]; /* index on g */\n\t\t\t\t}\n\t\t\t}\n\t\t\tq = network[smallpos];\n\n\t\t\t/* swap p (i) and q (smallpos) entries */\n\t\t\tif (i != smallpos) {\n\t\t\t\tj = q[0];\n\t\t\t\tq[0] = p[0];\n\t\t\t\tp[0] = j;\n\t\t\t\tj = q[1];\n\t\t\t\tq[1] = p[1];\n\t\t\t\tp[1] = j;\n\t\t\t\tj = q[2];\n\t\t\t\tq[2] = p[2];\n\t\t\t\tp[2] = j;\n\t\t\t\tj = q[3];\n\t\t\t\tq[3] = p[3];\n\t\t\t\tp[3] = j;\n\t\t\t}\n\n\t\t\t/* smallval entry is now in position i */\n\n\t\t\tif (smallval != previouscol) {\n\n\t\t\t\tnetindex[previouscol] = (startpos + i) >> 1;\n\n\t\t\t\tfor (j = previouscol + 1; j < smallval; j++) netindex[j] = i;\n\n\t\t\t\tpreviouscol = smallval;\n\t\t\t\tstartpos = i;\n\t\t\t}\n\t\t}\n\n\t\tnetindex[previouscol] = (startpos + maxnetpos) >> 1;\n\t\tfor (j = previouscol + 1; j < 256; j++) netindex[j] = maxnetpos; /* really 256 */\n\t};\n\n\t/*\n\t * Main Learning Loop ------------------\n\t */\n\n\tvar learn = function learn() {\n\n\t\tvar i;\n\t\tvar j;\n\t\tvar b;\n\t\tvar g;\n\t\tvar r;\n\t\tvar radius;\n\t\tvar rad;\n\t\tvar alpha;\n\t\tvar step;\n\t\tvar delta;\n\t\tvar samplepixels;\n\t\tvar p;\n\t\tvar pix;\n\t\tvar lim;\n\n\t\tif (lengthcount < minpicturebytes) samplefac = 1;\n\n\t\talphadec = 30 + ((samplefac - 1) / 3);\n\t\tp = thepicture;\n\t\tpix = 0;\n\t\tlim = lengthcount;\n\t\tsamplepixels = lengthcount / (3 * samplefac);\n\t\tdelta = (samplepixels / ncycles) | 0;\n\t\talpha = initalpha;\n\t\tradius = initradius;\n\n\t\trad = radius >> radiusbiasshift;\n\t\tif (rad <= 1) rad = 0;\n\n\t\tfor (i = 0; i < rad; i++) radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n\n\t\tif (lengthcount < minpicturebytes) step = 3;\n\n\t\telse if ((lengthcount % prime1) !== 0) step = 3 * prime1;\n\n\t\telse {\n\n\t\t\tif ((lengthcount % prime2) !== 0) step = 3 * prime2;\n\t\t\telse {\n\t\t\t\tif ((lengthcount % prime3) !== 0) step = 3 * prime3;\n\t\t\t\telse step = 3 * prime4;\n\t\t\t}\n\t\t}\n\n\t\ti = 0;\n\t\twhile (i < samplepixels) {\n\n\t\t\tb = (p[pix + 0] & 0xff) << netbiasshift;\n\t\t\tg = (p[pix + 1] & 0xff) << netbiasshift;\n\t\t\tr = (p[pix + 2] & 0xff) << netbiasshift;\n\t\t\tj = contest(b, g, r);\n\n\t\t\taltersingle(alpha, j, b, g, r);\n\t\t\tif (rad !== 0) alterneigh(rad, j, b, g, r); /* alter neighbours */\n\n\t\t\tpix += step;\n\t\t\tif (pix >= lim) pix -= lengthcount;\n\n\t\t\ti++;\n\n\t\t\tif (delta === 0) delta = 1;\n\n\t\t\tif (i % delta === 0) {\n\t\t\t\talpha -= alpha / alphadec;\n\t\t\t\tradius -= radius / radiusdec;\n\t\t\t\trad = radius >> radiusbiasshift;\n\n\t\t\t\tif (rad <= 1) rad = 0;\n\n\t\t\t\tfor (j = 0; j < rad; j++) radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n\t\t\t}\n\t\t}\n\t};\n\n\t/*\n\t ** Search for BGR values 0..255 (after net is unbiased) and return colour\n\t * index\n\t * ----------------------------------------------------------------------------\n\t */\n\n\tvar map = exports.map = function map(b, g, r) {\n\n\t\tvar i;\n\t\tvar j;\n\t\tvar dist;\n\t\tvar a;\n\t\tvar bestd;\n\t\tvar p;\n\t\tvar best;\n\n\t\tbestd = 1000; /* biggest possible dist is 256*3 */\n\t\tbest = -1;\n\t\ti = netindex[g]; /* index on g */\n\t\tj = i - 1; /* start at netindex[g] and work outwards */\n\n\t\twhile ((i < netsize) || (j >= 0)) {\n\n\t\t\tif (i < netsize) {\n\t\t\t\tp = network[i];\n\t\t\t\tdist = p[1] - g; /* inx key */\n\n\t\t\t\tif (dist >= bestd) i = netsize; /* stop iter */\n\n\t\t\t\telse {\n\n\t\t\t\t\ti++;\n\t\t\t\t\tif (dist < 0) dist = -dist;\n\t\t\t\t\ta = p[0] - b;\n\t\t\t\t\tif (a < 0) a = -a;\n\t\t\t\t\tdist += a;\n\n\t\t\t\t\tif (dist < bestd) {\n\t\t\t\t\t\ta = p[2] - r;\n\t\t\t\t\t\tif (a < 0) a = -a;\n\t\t\t\t\t\tdist += a;\n\n\t\t\t\t\t\tif (dist < bestd) {\n\t\t\t\t\t\t\tbestd = dist;\n\t\t\t\t\t\t\tbest = p[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (j >= 0) {\n\n\t\t\t\tp = network[j];\n\t\t\t\tdist = g - p[1]; /* inx key - reverse dif */\n\n\t\t\t\tif (dist >= bestd) j = -1; /* stop iter */\n\n\t\t\t\telse {\n\n\t\t\t\t\tj--;\n\t\t\t\t\tif (dist < 0) dist = -dist;\n\t\t\t\t\ta = p[0] - b;\n\t\t\t\t\tif (a < 0) a = -a;\n\t\t\t\t\tdist += a;\n\n\t\t\t\t\tif (dist < bestd) {\n\t\t\t\t\t\ta = p[2] - r;\n\t\t\t\t\t\tif (a < 0) a = -a;\n\t\t\t\t\t\tdist += a;\n\t\t\t\t\t\tif (dist < bestd) {\n\t\t\t\t\t\t\tbestd = dist;\n\t\t\t\t\t\t\tbest = p[3];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn (best);\n\t};\n\n\tvar process = exports.process = function process() {\n\t\tlearn();\n\t\tunbiasnet();\n\t\tinxbuild();\n\t\treturn colorMap();\n\t};\n\n\t/*\n\t * Unbias network to give byte values 0..255 and record position i to prepare\n\t * for sort\n\t * -----------------------------------------------------------------------------------\n\t */\n\n\tvar unbiasnet = function unbiasnet() {\n\n\t\tvar i;\n\t\tvar j;\n\n\t\tfor (i = 0; i < netsize; i++) {\n\t\t\tnetwork[i][0] >>= netbiasshift;\n\t\t\tnetwork[i][1] >>= netbiasshift;\n\t\t\tnetwork[i][2] >>= netbiasshift;\n\t\t\tnetwork[i][3] = i; /* record colour no */\n\t\t}\n\t};\n\n\t/*\n\t * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in\n\t * radpower[|i-j|]\n\t * ---------------------------------------------------------------------------------\n\t */\n\n\tvar alterneigh = function alterneigh(rad, i, b, g, r) {\n\n\t\tvar j;\n\t\tvar k;\n\t\tvar lo;\n\t\tvar hi;\n\t\tvar a;\n\t\tvar m;\n\t\tvar p;\n\n\t\tlo = i - rad;\n\t\tif (lo < -1) lo = -1;\n\n\t\thi = i + rad;\n\t\tif (hi > netsize) hi = netsize;\n\n\t\tj = i + 1;\n\t\tk = i - 1;\n\t\tm = 1;\n\n\t\twhile ((j < hi) || (k > lo)) {\n\t\t\ta = radpower[m++];\n\n\t\t\tif (j < hi) {\n\t\t\t\tp = network[j++];\n\n\t\t\t\ttry {\n\t\t\t\t\tp[0] -= (a * (p[0] - b)) / alpharadbias;\n\t\t\t\t\tp[1] -= (a * (p[1] - g)) / alpharadbias;\n\t\t\t\t\tp[2] -= (a * (p[2] - r)) / alpharadbias;\n\t\t\t\t} catch (e) {} // prevents 1.3 miscompilation\n\t\t\t}\n\n\t\t\tif (k > lo) {\n\t\t\t\tp = network[k--];\n\n\t\t\t\ttry {\n\t\t\t\t\tp[0] -= (a * (p[0] - b)) / alpharadbias;\n\t\t\t\t\tp[1] -= (a * (p[1] - g)) / alpharadbias;\n\t\t\t\t\tp[2] -= (a * (p[2] - r)) / alpharadbias;\n\t\t\t\t} catch (e) {}\n\t\t\t}\n\t\t}\n\t};\n\n\t/*\n\t * Move neuron i towards biased (b,g,r) by factor alpha\n\t * ----------------------------------------------------\n\t */\n\n\tvar altersingle = function altersingle(alpha, i, b, g, r) {\n\n\t\t/* alter hit neuron */\n\t\tvar n = network[i];\n\t\tn[0] -= (alpha * (n[0] - b)) / initalpha;\n\t\tn[1] -= (alpha * (n[1] - g)) / initalpha;\n\t\tn[2] -= (alpha * (n[2] - r)) / initalpha;\n\t};\n\n\t/*\n\t * Search for biased BGR values ----------------------------\n\t */\n\n\tvar contest = function contest(b, g, r) {\n\n\t\t/* finds closest neuron (min dist) and updates freq */\n\t\t/* finds best neuron (min dist-bias) and returns position */\n\t\t/* for frequently chosen neurons, freq[i] is high and bias[i] is negative */\n\t\t/* bias[i] = gamma*((1/netsize)-freq[i]) */\n\n\t\tvar i;\n\t\tvar dist;\n\t\tvar a;\n\t\tvar biasdist;\n\t\tvar betafreq;\n\t\tvar bestpos;\n\t\tvar bestbiaspos;\n\t\tvar bestd;\n\t\tvar bestbiasd;\n\t\tvar n;\n\n\t\tbestd = ~ (1 << 31);\n\t\tbestbiasd = bestd;\n\t\tbestpos = -1;\n\t\tbestbiaspos = bestpos;\n\n\t\tfor (i = 0; i < netsize; i++) {\n\t\t\tn = network[i];\n\t\t\tdist = n[0] - b;\n\t\t\tif (dist < 0) dist = -dist;\n\t\t\ta = n[1] - g;\n\t\t\tif (a < 0) a = -a;\n\t\t\tdist += a;\n\t\t\ta = n[2] - r;\n\t\t\tif (a < 0) a = -a;\n\t\t\tdist += a;\n\n\t\t\tif (dist < bestd) {\n\t\t\t\tbestd = dist;\n\t\t\t\tbestpos = i;\n\t\t\t}\n\n\t\t\tbiasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n\n\t\t\tif (biasdist < bestbiasd) {\n\t\t\t\tbestbiasd = biasdist;\n\t\t\t\tbestbiaspos = i;\n\t\t\t}\n\n\t\t\tbetafreq = (freq[i] >> betashift);\n\t\t\tfreq[i] -= betafreq;\n\t\t\tbias[i] += (betafreq << gammashift);\n\t\t}\n\n\t\tfreq[bestpos] += beta;\n\t\tbias[bestpos] -= betagamma;\n\t\treturn (bestbiaspos);\n\t};\n\n\tNeuQuant.apply(this, arguments);\n\treturn exports;\n};\nfunction encode64(input) {\n\tvar output = \"\", i = 0, l = input.length,\n\tkey = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\", \n\tchr1, chr2, chr3, enc1, enc2, enc3, enc4;\n\twhile (i < l) {\n\t\tchr1 = input.charCodeAt(i++);\n\t\tchr2 = input.charCodeAt(i++);\n\t\tchr3 = input.charCodeAt(i++);\n\t\tenc1 = chr1 >> 2;\n\t\tenc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n\t\tenc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n\t\tenc4 = chr3 & 63;\n\t\tif (isNaN(chr2)) enc3 = enc4 = 64;\n\t\telse if (isNaN(chr3)) enc4 = 64;\n\t\toutput = output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4);\n\t}\n\treturn output;\n}\n"
  },
  {
    "path": "assets/page.html",
    "content": "<!DOCTYPE html>\n<head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <link rel=\"stylesheet\" href=\"bootstrap.min.css\" media=\"screen\">\n    <link rel=\"stylesheet\" href=\"styles.css?vary={VERSION}\" media=\"screen\">\n    <link rel=\"stylesheet\" href=\"styles-user.css?vary={VERSION}\" media=\"screen\">\n    <title>{TITLE}</title>\n    <meta name=\"description\" content=\"{CLEAN_DESCRIPTION}\" />\n    <script src=\"jquery.min.js\"></script>\n</head>\n<body>\n    <div class=\"content_box\">\n        <h1>{TITLE}</h1>\n        <h4>{DESCRIPTION}</h4>\n        <noscript>This page requires JavaScript to work. Don't worry, it's all local to the current page, and open source on GitHub.</noscript>\n        <hr>\n        <div class=\"top_nav_bar\" id=\"top_nav_bar\">\n            <div class=\"accordion navigation_accordion\" id=\"navigation_accordion\">\n                <div class=\"accordion-item\">\n                    <h2 class=\"accordion-header\" id=\"navigation_accordion_heading\">\n                        <button class=\"accordion-button\" type=\"button\" id=\"toggle_nav_button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navigation_accordion_collapse\" aria-expanded=\"true\" aria-controls=\"navigation_accordion_collapse\">Navigation</button>\n                    </h2>\n                    <div id=\"navigation_accordion_collapse\" class=\"accordion-collapse collapse show\" aria-labelledby=\"navigation_accordion_heading\" data-bs-parent=\"navigation_accordion\">\n                        <div class=\"accordion-body\">\n                            <div>\n                                <div class=\"accordion advanced_settings_section\" id=\"settings_accordion\">\n                                    <div class=\"accordion-item\">\n                                        <h2 class=\"accordion-header\" id=\"setting_accordion_heading\">\n                                            <button class=\"accordion-button collapsed\" id=\"toggle_adv_button\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#settings_accordion_collapse\" aria-expanded=\"false\" aria-controls=\"settings_accordion_collapse\">Advanced Settings</button>\n                                        </h2>\n                                        <div id=\"settings_accordion_collapse\" class=\"accordion-collapse collapse\" aria-labelledby=\"setting_accordion_heading\" data-bs-parent=\"#settings_accordion\">\n                                            <div class=\"accordion-body\">\n                                                {ADVANCED_SETTINGS}\n                                            </div>\n                                        </div>\n                                    </div>\n                                </div>\n                            </div>\n                            <br>\n                            {CONTENT}\n                            <center>\n                                <input class=\"form-check-input\" type=\"checkbox\" id=\"showDescriptions\" checked=\"true\" autocomplete=\"off\" onchange=\"javascript:toggleDescriptions()\"> <label class=\"form-check-label\" for=\"showDescriptions\" title=\"Uncheck this to focus on the grid. Check it to see the full descriptions of each option.\">Show descriptions of axes and values</label>\n                                &emsp;&emsp;<input class=\"form-check-input\" type=\"checkbox\" autocomplete=\"off\" value=\"\" id=\"autoScaleImages\"> <label class=\"form-check-label\" for=\"autoScaleImages\">Auto-scale images to viewport width</label>\n                                &emsp;&emsp;<input class=\"form-check-input\" type=\"checkbox\" autocomplete=\"off\" value=\"\" id=\"stickyNavigation\"> <label class=\"form-check-label\" for=\"stickyNavigation\">Sticky navigation</label>\n                                &emsp;&emsp;<input class=\"form-check-input\" type=\"checkbox\" autocomplete=\"off\" checked id=\"stickyLabels\"> <label class=\"form-check-label\" for=\"stickyLabels\">Sticky labels</label>\n                                &emsp;&emsp;<span id=\"score_setting\">Score Display: <select id=\"score_display\"><option>None</option><option>Thin Outline</option><option>Thick Bars</option><option>Heatmap</option></select></span>\n                            </center>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div id=\"save_image_helper\" class=\"save_image_area\">\n                <button onclick=\"makeImage()\">Save Image Of Current View</button> <select title=\"Image Type\" id=\"makeimage_type\"><option>jpeg</option><option>png</option></select> <select title=\"Image Size\" id=\"makeimage_size\"><option selected>1x</option><option>0.75x</option><option>0.5x</option><option>0.25x</option></select>\n                &emsp;<button onclick=\"makeGif()\">Create Axis GIF Animation</button> <select title=\"Axis\" id=\"makegif_axis\"><option value=\"x-axis\">X Axis</option></select> <select title=\"GIF Size\" id=\"makegif_size\"><option>1x</option><option>0.75x</option><option selected>0.5x</option><option>0.25x</option></select> <select title=\"GIF Speed\" id=\"makegif_speed\"><option>1/s</option><option>2/s</option><option>3/s</option><option selected>4/s</option><option>5/s</option><option>10/s</option></select><select title=\"GIF Direction\" id=\"makegif_direction\"><option>Forwards</option><option>Backwards</option></select>\n                <div id=\"save_image_info\" style=\"display: none;\">Here's your image! To share it, just use right click -> Copy image or Save Image As</div>\n            </div>\n        </div>\n        <div class=\"image_table_box\">\n            <table class=\"image_table\" id=\"image_table\"></table>\n            <table id=\"image_script_dump\"></table>\n        </div>\n    </div>\n    <div class=\"modal modal-fullscreen popup_modal_background\" id=\"image_info_modal\"></div>\n    <div class=\"modal\" tabindex=\"-1\" id=\"save_image_output_modal\">\n        <div class=\"modal-dialog modal-xl\">\n            <div class=\"modal-content\">\n                <div class=\"modal-header\">\n                    <h5 class=\"modal-title\">Here's your image!</h5>\n                    <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button>\n                </div>\n                <div class=\"modal-body\">\n                    <p>To share it, just use right click -> Copy image or Save Image As.</p>\n                    <div id=\"save_image_output\" class=\"save_image_output\"></div>\n                </div>\n            </div>\n        </div>\n    </div>\n    <br><div style=\"width:256px;height:512px;\"></div> <!-- Spacer to reduce screen-jumping if images load while you're scrolled down -->\n    <footer>\n        <center>\n            <hr>\n            Created by: {AUTHOR}\n            <br>The technology that powers this page is <a href=\"https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script\">Infinity Grid Generator</a>, published under the MIT license by Alex 'mcmonkey' Goodwin.\n            <br>This software allows users to generate pages with any content they desire. Therefore, content on this page (images, text, etc.) is the property of whoever generated this specific page.\n            <br>{EXTRA_FOOTER}\n            <br>Made using the <a href=\"https://bootswatch.com/darkly/\">Darkly Bootstrap Theme</a> by Thomas Park, which was released under the <a href=\"https://github.com/thomaspark/bootswatch/blob/95df99d76147797cbcb1014b639805add2327f65/LICENSE\">MIT License</a>.\n            <br>Gifs are generated using <a href=\"https://github.com/antimatter15/jsgif\">JSGif</a>, which was released under the <a href=\"https://github.com/antimatter15/jsgif/blob/b46429c50a53d23b762d6ebb00b375aece3ed843/LICENSE\">MIT License</a>.\n            <br>\n            <br><div style=\"width:256px;height:512px;\"></div>\n        </center>\n    </footer>\n    <script src=\"bootstrap.bundle.min.js\"></script>\n    <script src=\"jsgif.js\"></script>\n    <script src=\"data.js?vary={VERSION}\"></script>\n    <script src=\"proc.js?vary={VERSION}\"></script>\n</body>\n"
  },
  {
    "path": "assets/proc.js",
    "content": "/*\n * This file is part of Infinity Grid Generator, view the README.md at https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script for more information.\n*/\n\nlet suppressUpdate = true;\nlet file_extensions_alt = {};\n\nfunction loadData() {\n    let rawHash = window.location.hash;\n    document.getElementById('x_' + rawData.axes[0].id).click();\n    document.getElementById('x2_none').click();\n    document.getElementById('y2_none').click();\n    let makegif_axis = document.getElementById('makegif_axis');\n    // rawData.ext/title/description\n    for (var axis of rawData.axes) {\n        // axis.id/title/description\n        for (var val of axis.values) {\n            // val.key/title/description/show\n            let clicktab = getNavValTab(axis.id, val.key);\n            clicktab.addEventListener('click', fillTable);\n            if (!val.show) {\n                setShowVal(axis.id, val.key, false);\n            }\n        }\n        for (var prefix of ['x_', 'y_', 'x2_', 'y2_']) {\n            document.getElementById(prefix + axis.id).addEventListener('click', fillTable);\n        }\n        for (var label of ['x2_none', 'y2_none']) {\n            document.getElementById(label).addEventListener('click', fillTable);\n        }\n        makegif_axis.appendChild(new Option(axis.title, axis.id));\n    }\n    console.log(`Loaded data for '${rawData.title}'`);\n    document.getElementById('autoScaleImages').addEventListener('change', updateScaling);\n    document.getElementById('stickyNavigation').addEventListener('change', toggleTopSticky);\n    document.getElementById('stickyLabels').addEventListener('change', toggleLabelSticky);\n    document.getElementById('toggle_nav_button').addEventListener('click', updateTitleSticky);\n    document.getElementById('toggle_adv_button').addEventListener('click', updateTitleSticky);\n    document.getElementById('showDescriptions').checked = rawData.defaults.show_descriptions;\n    document.getElementById('autoScaleImages').checked = rawData.defaults.autoscale;\n    document.getElementById('stickyNavigation').checked = rawData.defaults.sticky;\n    document.getElementById('stickyLabels').checked = rawData.defaults.sticky_labels;\n    document.getElementById('score_display').addEventListener('click', fillTable);\n    document.getElementById('score_setting').style.display = typeof getScoreFor == 'undefined' ? 'none' : 'inline-block';\n    updateStylesToMatchInputs();\n    for (var axis of ['x', 'y', 'x2', 'y2']) {\n        if (rawData.defaults[axis] != '') {\n            document.getElementById(axis + '_' + rawData.defaults[axis]).click();\n        }\n    }\n    applyHash(rawHash);\n    suppressUpdate = false;\n    fillTable();\n    startAutoScroll();\n    if (rawData.will_run) {\n        setTimeout(checkForUpdates, 5000);\n    }\n}\n\nfunction getExtension(filePath) {\n    if (filePath in file_extensions_alt) {\n        return file_extensions_alt[filePath];\n    }\n    return rawData.ext;\n}\n\n/** External callable. */\nfunction fix_video(path) {\n    let ext = getExtension(path);\n    let matches = document.querySelectorAll(`img[data-img_path=\"${path}\"]`);\n    for (let match of matches) {\n        if (ext != 'webm' && ext != 'mp4') {\n            if (!match.src.endsWith(ext)) {\n                match.src = `${path}.${ext}`;\n            }\n            continue;\n        }\n        if (match.tagName == 'VIDEO') {\n            continue;\n        }\n        let video = document.createElement('video');\n        video.loop = true;\n        video.muted = true;\n        video.autoplay = true;\n        video.classList = match.classList;\n        video.dataset.img_path = match.dataset.img_path;\n        video.onclick = \"doPopupFor(this)\";\n        video.onerror = \"setImgPlaceholder(this)\";\n        let source = document.createElement('source');\n        source.src = `${path}.${ext}`;\n        source.type = `video/${ext}`;\n        video.appendChild(source);\n        match.parentElement.replaceChild(video, match);\n    }\n}\n\nfunction updateStylesToMatchInputs() {\n    toggleTopSticky();\n    toggleLabelSticky();\n}\n\nfunction getAxisById(id) {\n    return rawData.axes.find(axis => axis.id == id);\n}\n\nfunction getNextAxis(axes, startId) {\n    var next = false;\n    for (var subAxis of axes) {\n        if (subAxis.id == startId) {\n            next = true;\n        }\n        else if (next) {\n            return subAxis;\n        }\n    }\n    return null;\n}\n\nfunction getSelectedValKey(axis) {\n    for (var subVal of axis.values) {\n        if (window.getComputedStyle(document.getElementById('tab_' + axis.id + '__' + subVal.key)).display != 'none') {\n            return subVal.path;\n        }\n    }\n    return null;\n}\n\nvar popoverLastImg = null;\n\nfunction clickRowImage(rows, x, y) {\n    $('#image_info_modal').modal('hide');\n    var columns = rows[y].getElementsByTagName('td');\n    columns[x].getElementsByTagName('img')[0].click();\n}\n\nwindow.addEventListener('keydown', function(kbevent) {\n    if ($('#image_info_modal').is(':visible')) {\n        if (kbevent.key == 'Escape') {\n            $('#image_info_modal').modal('toggle');\n            kbevent.preventDefault();\n            kbevent.stopPropagation();\n            return false;\n        }\n        var tableElem = document.getElementById('image_table');\n        var rows = tableElem.getElementsByTagName('tr');\n        var matchedRow = null;\n        var x = 0, y = 0;\n        for (var row of rows) {\n            var columns = row.getElementsByTagName('td');\n            for (var column of columns) {\n                var images = column.getElementsByTagName('img');\n                if (images.length == 1 && images[0] == popoverLastImg) {\n                    matchedRow = row;\n                    break;\n                }\n                x++;\n            }\n            if (matchedRow != null) {\n                break;\n            }\n            x = 0;\n            y++;\n        }\n        if (matchedRow == null) {\n            return;\n        }\n        if (kbevent.key == 'ArrowLeft') {\n            if (x > 1) {\n                x--;\n                clickRowImage(rows, x, y);\n            }\n        }\n        else if (kbevent.key == 'ArrowRight') {\n            x++;\n            var columns = matchedRow.getElementsByTagName('td');\n            if (columns.length > x) {\n                clickRowImage(rows, x, y);\n            }\n        }\n        else if (kbevent.key == 'ArrowUp') {\n            if (y > 1) {\n                y--;\n                clickRowImage(rows, x, y);\n            }\n        }\n        else if (kbevent.key == 'ArrowDown') {\n            y++;\n            if (rows.length > y) {\n                clickRowImage(rows, x, y);\n            }\n        }\n        else {\n            return;\n        }\n        kbevent.preventDefault();\n        kbevent.stopPropagation();\n        return false;\n    }\n    var elem = document.activeElement;\n    if (!elem.id.startsWith('clicktab_')) {\n        return;\n    }\n    var axisId = elem.id.substring('clicktab_'.length);\n    var splitIndex = axisId.lastIndexOf('__');\n    axisId = axisId.substring(0, splitIndex);\n    var axis = getAxisById(axisId);\n    if (kbevent.key == 'ArrowLeft') {\n        var tabPage = document.getElementById('tablist_' + axis.id);\n        var tabs = tabPage.getElementsByClassName('nav-link');\n        var newTab = clickTabAfterActiveTab(Array.from(tabs).reverse());\n        newTab.focus({ preventScroll: true });\n    }\n    else if (kbevent.key == 'ArrowRight') {\n        var tabPage = document.getElementById('tablist_' + axis.id);\n        var tabs = tabPage.getElementsByClassName('nav-link');\n        var newTab = clickTabAfterActiveTab(tabs);\n        newTab.focus({ preventScroll: true });\n    }\n    else if (kbevent.key == 'ArrowUp') {\n        var next = getNextAxis(Array.from(rawData.axes).reverse(), axisId);\n        if (next != null) {\n            var selectedKey = getSelectedValKey(next);\n            var swapToTab = getNavValTab(next.id, selectedKey);\n            swapToTab.focus({ preventScroll: true });\n        }\n    }\n    else if (kbevent.key == 'ArrowDown') {\n        var next = getNextAxis(rawData.axes, axisId);\n        if (next != null) {\n            var selectedKey = getSelectedValKey(next);\n            var swapToTab = getNavValTab(next.id, selectedKey);\n            swapToTab.focus({ preventScroll: true });\n        }\n    }\n    else {\n        return;\n    }\n    kbevent.preventDefault();\n    kbevent.stopPropagation();\n    return false;\n}, true);\n\nfunction escapeHtml(text) {\n    if (typeof text != 'string') {\n        return text;\n    }\n    return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\"', '&quot;').replaceAll(\"'\", '&#039;');\n}\n\nfunction unescapeHtml(text) {\n    return text.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '\"').replaceAll('&#039;', \"'\").replaceAll('&amp;', '&');\n}\n\nfunction canShowVal(axis, val) {\n    return document.getElementById(`showval_${axis}__${val}`).checked;\n}\n\nfunction setShowVal(axis, val, show) {\n    document.getElementById(`showval_${axis}__${val}`).checked = show;\n    getNavValTab(axis, val).classList.toggle('tab_hidden', !show);\n}\n\nfunction getNavValTab(axis, val) {\n    return document.getElementById(`clicktab_${axis}__${val}`);\n}\n\nfunction percentToRedGreen(percent) {\n    return `color-mix(in srgb, red, green ${percent}%)`;\n}\n\nlet scoreTrackCounter = 0;\nlet scoreUpdates = [];\nlet lastScoreBump = Date.now();\nlet scoreBumpTracker = null;\nlet scoreMin = 0, scoreMax = 1;\n\nfunction getXAxisContent(x, y, xAxis, yval, x2Axis, x2val, y2Axis, y2val) {\n    let scriptDump = document.getElementById('image_script_dump');\n    let imgPath = [];\n    let index = 0;\n    for (let subAxis of rawData.axes) {\n        if (subAxis.id == x) {\n            index = imgPath.length;\n            imgPath.push(null);\n        }\n        else if (subAxis.id == y) {\n            imgPath.push(yval.path);\n        }\n        else if (x2Axis != null && subAxis.id == x2Axis.id) {\n            imgPath.push(x2val.path);\n        }\n        else if (y2Axis != null && subAxis.id == y2Axis.id) {\n            imgPath.push(y2val.path);\n        }\n        else {\n            imgPath.push(getSelectedValKey(subAxis));\n        }\n    }\n    let newContent = '';\n    let subInd = 0;\n    let scoreDisplay = document.getElementById('score_display').value;\n    for (let xVal of xAxis.values) {\n        subInd++;\n        if (!canShowVal(xAxis.id, xVal.key)) {\n            continue;\n        }\n        imgPath[index] = xVal.path;\n        let slashed = imgPath.join('/');\n        let ext = getExtension(slashed);\n        let actualUrl = slashed + '.' + ext;\n        let id = scoreTrackCounter++;\n        newContent += `<td id=\"td-img-${id}\"><span></span>`;\n        if (ext == 'mp4' || ext == 'webm') {\n            newContent += `<video loop autoplay muted class=\"table_img\" data-img_path=\"${slashed}\" onclick=\"doPopupFor(this)\" onerror=\"setImgPlaceholder(this)\" alt=\"${actualUrl}\"><source src=\"${actualUrl}\" type=\"video/${ext}\"></source></video>`;\n        }\n        else {\n            newContent += `<img class=\"table_img\" data-img_path=\"${slashed}\" onclick=\"doPopupFor(this)\" onerror=\"setImgPlaceholder(this)\" src=\"${actualUrl}\" alt=\"${actualUrl}\" />`;\n        }\n        newContent += '</td>';\n        let newScr = null;\n        if (typeof getMetadataScriptFor != 'undefined') {\n            newScr = document.createElement('script');\n            newScr.src = getMetadataScriptFor(slashed);\n        }\n        let doScores = scoreDisplay != 'None' && typeof getScoreFor != 'undefined';\n        if (doScores) {\n            scoreUpdates.push(() => {\n                let score = getScoreFor(slashed);\n                if (score) {\n                    score = (score - scoreMin) / (scoreMax - scoreMin);\n                    let elem = document.getElementById(`td-img-${id}`);\n                    let color = percentToRedGreen(score * 100);\n                    let blockColor = '';\n                    if (scoreDisplay == 'Thin Outline')\n                    {\n                        let xborder = `border-top: 2px solid ${color}; border-bottom: 2px solid ${color};`;\n                        let yborder = `border-left: 2px solid ${color}; border-right: 2px solid ${color};`;\n                        elem.getElementsByTagName('img')[0].style = `${xborder} ${yborder}`;\n                    }\n                    else if (scoreDisplay == 'Thick Bars')\n                    {\n                        elem.getElementsByTagName('img')[0].style = `border-top: 10px solid ${color}; border-left: 10px solid ${color};`;\n                    }\n                    else if (scoreDisplay == 'Heatmap')\n                    {\n                        blockColor = `color-mix(in srgb, ${color} 50%, transparent)`;\n                    }\n                    elem.firstChild.innerHTML = `<div style=\"position: relative; width: 0; height: 0\"><div style=\"position: absolute; left: 0; z-index: 20;\">${Math.round(score * 100)}%</div><div class=\"heatmapper\" style=\"position: absolute; left: 0; width: 100px; height: 100px; z-index: 10; background-color: ${blockColor}\"></div></div>`;\n                }\n            });\n        }\n        if (newScr != null) {\n            newScr.onload = () => {\n                setTimeout(() => {\n                    lastScoreBump = Date.now();\n                    let ext = file_extensions_alt[slashed];\n                    if (ext && !actualUrl.endsWith(ext)) {\n                        fix_video(slashed);\n                    }\n                }, 1);\n                if (scoreBumpTracker == null) {\n                    scoreBumpTracker = setInterval(() => {\n                        if (Date.now() - lastScoreBump > 300) {\n                            clearInterval(scoreBumpTracker);\n                            scoreBumpTracker = null;\n                            if (doScores) {\n                                scoreMin = 1;\n                                scoreMax = 0;\n                                for (let image of document.getElementsByClassName('table_img')) {\n                                    let score = getScoreFor(image.dataset.img_path);\n                                    if (score) {\n                                        scoreMin = Math.min(scoreMin, score);\n                                        scoreMax = Math.max(scoreMax, score);\n                                    }\n                                }\n                                let upds = scoreUpdates;\n                                scoreUpdates = [];\n                                for (let update of upds) {\n                                    update();\n                                }\n                                updateScaling();\n                            }\n                        }\n                    }, 100);\n                }\n            };\n        }\n        if (newScr) {\n            scriptDump.appendChild(newScr);\n        }\n    }\n    return newContent;\n}\n\nfunction setImgPlaceholder(img) {\n    if (!img.parentElement) {\n        return;\n    }\n    img.onerror = undefined;\n    img.dataset.errored_src = img.src;\n    img.src = 'placeholder.png';\n    if (rawData.min_width) {\n        img.width = rawData.min_width;\n        img.height = rawData.min_height;\n    }\n    setImageScale(img, getWantedScaling());\n}\n\nfunction optDescribe(isFirst, val) {\n    return isFirst && val != null ? '<span title=\"' + escapeHtml(val.description) + '\"><b>' + escapeHtml(val.title) + '</b></span><br>' : (val != null ? '<br>' : '');\n}\n\nfunction fillTable() {\n    if (suppressUpdate) {\n        return;\n    }\n    var x = getCurrentSelectedAxis('x');\n    var y = getCurrentSelectedAxis('y');\n    var x2 = getCurrentSelectedAxis('x2');\n    var y2 = getCurrentSelectedAxis('y2');\n    console.log('Do fill table, x=' + x + ', y=' + y + ', x2=' + x2 + ', y2=' + y2);\n    var xAxis = getAxisById(x);\n    var yAxis = getAxisById(y);\n    var x2Axis = x2 == 'None' || x2 == x || x2 == y ? null : getAxisById(x2);\n    var y2Axis = y2 == 'None' || y2 == x2 || y2 == x || y2 == y ? null : getAxisById(y2);\n    var table = document.getElementById('image_table');\n    var newContent = '<tr id=\"image_table_header\" class=\"sticky_top\"><th></th>';\n    var superFirst = true;\n    document.getElementById('image_script_dump').innerHTML = '';\n    for (var x2val of (x2Axis == null ? [null] : x2Axis.values)) {\n        if (x2val != null && !canShowVal(x2Axis.id, x2val.key)) {\n            continue;\n        }\n        var x2first = true;\n        for (var val of xAxis.values) {\n            if (!canShowVal(xAxis.id, val.key)) {\n                continue;\n            }\n            newContent += `<th${(superFirst ? '' : ' class=\"superaxis_second\"')} title=\"${val.description.replaceAll('\"', '&quot;')}\">${optDescribe(x2first, x2val)}<b>${escapeHtml(val.title)}</b></th>`;\n            x2first = false;\n        }\n        superFirst = !superFirst;\n    }\n    newContent += '</tr>';\n    superFirst = true;\n    for (var y2val of (y2Axis == null ? [null] : y2Axis.values)) {\n        if (y2val != null && !canShowVal(y2Axis.id, y2val.key)) {\n            continue;\n        }\n        var y2first = true;\n        for (var val of yAxis.values) {\n            if (!canShowVal(yAxis.id, val.key)) {\n                continue;\n            }\n            newContent += `<tr><td class=\"axis_label_td${(superFirst ? '' : ' superaxis_second')}\" title=\"${escapeHtml(val.description)}\">${optDescribe(y2first, y2val)}<b>${escapeHtml(val.title)}</b></td>`;\n            y2first = false;\n            for (var x2val of (x2Axis == null ? [null] : x2Axis.values)) {\n                if (x2val != null && !canShowVal(x2Axis.id, x2val.key)) {\n                    continue;\n                }\n                newContent += getXAxisContent(x, y, xAxis, val, x2Axis, x2val, y2Axis, y2val);\n            }\n            newContent += '</tr>';\n            if (x == y) {\n                break;\n            }\n        }\n        superFirst = !superFirst;\n    }\n    table.innerHTML = newContent;\n    updateScaling();\n}\n\nfunction getCurrentSelectedAxis(axisPrefix) {\n    var id = document.querySelector(`input[name=\"${axisPrefix}_axis_selector\"]:checked`).id;\n    var index = id.indexOf('_');\n    return id.substring(index + 1);\n}\n\nfunction getShownItemsOfAxis(axis) {\n    return axis.values.filter(val => canShowVal(axis.id, val.key));\n}\n\nfunction getWantedScaling() {\n    if (!document.getElementById('autoScaleImages').checked) {\n        return 0;\n    }\n    var x = getCurrentSelectedAxis('x');\n    var xAxis = getAxisById(x);\n    var count = getShownItemsOfAxis(xAxis).length;\n    var x2 = getCurrentSelectedAxis('x2');\n    if (x2 != 'none') {\n        var x2Axis = getAxisById(x2);\n        count *= getShownItemsOfAxis(x2Axis).length;\n    }\n    return (90 / count);\n}\n\nfunction setImageScale(image, percent) {\n    let heatmapper = image.parentElement.getElementsByClassName('heatmapper')[0];\n    if (percent == 0) {\n        image.style.width = '';\n        image.style.height = '';\n        if (heatmapper) {\n            heatmapper.style.width = `${image.clientWidth}px`;\n            heatmapper.style.height = `${image.clientWidth}px`;\n        }\n    }\n    else {\n        image.style.width = percent + 'vw';\n        if (heatmapper) {\n            heatmapper.style.width = percent + 'vw';\n            heatmapper.style.height = percent * (parseFloat(image.clientWidth) / parseFloat(image.clientHeight)) + 'vw';\n        }\n        let width = image.getAttribute('width');\n        let height = image.getAttribute('height');\n        if (width != null && height != null) { // Rescale placeholders cleanly\n            image.style.height = (percent * (parseFloat(height) / parseFloat(width))) + 'vw';\n        }\n        else {\n            image.style.height = '';\n        }\n    }\n}\n\nfunction updateScaling() {\n    let percent = getWantedScaling();\n    for (var image of document.getElementById('image_table').getElementsByClassName('table_img')) {\n        setImageScale(image, percent);\n    }\n    updateTitleSticky();\n}\n\nfunction toggleDescriptions() {\n    var show = document.getElementById('showDescriptions').checked;\n    for (var cName of ['tabval_subdiv', 'axis_table_cell']) {\n        for (var elem of document.getElementsByClassName(cName)) {\n            elem.classList.toggle('tab_hidden', !show);\n        }\n    }\n    updateTitleSticky();\n}\n\nfunction toggleShowAllAxis(axisId) {\n    var axis = getAxisById(axisId);\n    var hide = axis.values.some(val => {\n        return canShowVal(axisId, val.key);\n    });\n    for (var val of axis.values) {\n        setShowVal(axisId, val.key, !hide);\n    }\n    fillTable();\n}\n\nfunction toggleShowVal(axis, val) {\n    var show = canShowVal(axis, val);\n    let element = getNavValTab(axis, val);\n    element.classList.toggle('tab_hidden', !show);\n    if (!show && element.classList.contains('active')) {\n        var next = [...element.parentElement.parentElement.getElementsByClassName('nav-link')].filter(e => !e.classList.contains('tab_hidden'));\n        if (next.length > 0) {\n            next[0].click();\n        }\n    }\n    fillTable();\n}\n\nvar anyRangeActive = false;\n\nfunction enableRange(id) {\n    var range = document.getElementById('range_tablist_' + id);\n    var label = document.getElementById('label_range_tablist_' + id);\n    range.oninput = function() {\n        anyRangeActive = true;\n        label.innerText = (range.value / 2) + ' seconds';\n    };\n    var tabPage = document.getElementById('tablist_' + id);\n    return {\n        range,\n        counter: 0,\n        tabs: tabPage.getElementsByClassName('nav-link')\n    };\n}\n\nfunction clickTabAfterActiveTab(tabs) {\n    var firstTab = null;\n    var foundActive = false;\n    var nextTab = Array.from(tabs).find(tab => {\n        var isActive = tab.classList.contains('active');\n        var isHidden = tab.classList.contains('tab_hidden');\n        if (!isHidden && !isActive && !firstTab) {\n            firstTab = tab;\n        }\n        if (isActive) {\n            foundActive = true;\n            return false;\n        }\n        return (foundActive && !isHidden);\n    }) || firstTab;\n\n    if (nextTab) {\n        nextTab.click();\n    }\n    return nextTab;\n}\n\nconst timer = ms => new Promise(res => setTimeout(res, ms));\n\nasync function startAutoScroll() {\n    var rangeSet = [];\n    for (var axis of rawData.axes) {\n        rangeSet.push(enableRange(axis.id));\n    }\n    while (true) {\n        await timer(500);\n        if (!anyRangeActive) {\n            continue;\n        }\n        for (var data of rangeSet) {\n            if (data.range.value <= 0) {\n                continue;\n            }\n            data.counter++;\n            if (data.counter < data.range.value) {\n                continue;\n            }\n            data.counter = 0;\n            clickTabAfterActiveTab(data.tabs);\n        }\n    }\n}\n\nfunction crunchMetadata(parts) {\n    if (!('metadata' in rawData)) {\n        return {};\n    }\n    var initialData = structuredClone(rawData.metadata);\n    if (!initialData) {\n        return {};\n    }\n    for (var index = 0; index < parts.length; index++) {\n        var part = parts[index];\n        var axis = rawData.axes[index];\n        var actualVal = axis.values.find(val => val.key == part);\n        if (actualVal == null) {\n            return { 'error': `metadata parsing failed for part ${index}: ${part}` };\n        }\n        for (var [key, value] of Object.entries(actualVal.params)) {\n            key = key.replaceAll(' ', '');\n            if (typeof(crunchParamHook) == 'undefined' || !crunchParamHook(initialData, key, value)) {\n                initialData[key] = value;\n            }\n        }\n    }\n    return initialData;\n}\n\nfunction doPopupFor(img) {\n    popoverLastImg = img;\n    let modalElem = document.getElementById('image_info_modal');\n    let metaText;\n    if (typeof getMetadataForImage != 'undefined') {\n        metaText = getMetadataForImage(img);\n    }\n    else {\n        let imgPath = img.dataset.img_path.split('/');\n        let metaData = crunchMetadata(imgPath);\n        metaText = typeof(formatMetadata) == 'undefined' ? JSON.stringify(metaData) : formatMetadata(metaData);\n    }\n    let params = escapeHtml(metaText).replaceAll('\\n', '\\n<br>');\n    let text = 'Image: ' + img.alt + (params.length > 1 ? ', parameters: <br>' + params : '<br>(parameters hidden)');\n    modalElem.innerHTML = `<div class=\"modal-dialog\" style=\"display:none\">(click outside image to close)</div><div class=\"modal_inner_div\"><img onclick=\"$('#image_info_modal').modal('hide')\" class=\"popup_modal_img\" src=\"${img.src}\"><br><div class=\"popup_modal_undertext\">${text}</div>`;\n    $('#image_info_modal').modal('toggle');\n}\n\nfunction updateTitleStickyDirect() {\n    var height = Math.round(document.getElementById('top_nav_bar').getBoundingClientRect().height);\n    var header = document.getElementById('image_table_header');\n    if (header.style.top != height + 'px') { // This check is to reduce the odds of the browser yelling at us\n        header.style.top = height + 'px';\n    }\n}\n\nfunction updateTitleSticky() {\n    var header = document.getElementById('image_table_header');\n    if (!header) {\n        return;\n    }\n    updateHash();\n    var topBar = document.getElementById('top_nav_bar');\n    if (!topBar.classList.contains('sticky_top')) {\n        header.style.top = '0';\n        return;\n    }\n    // client rect is dynamically animated, so, uh, just hack it for now.\n    // TODO: Actually smooth attachment.\n    var rate = 50;\n    for (var time = 0; time <= 500; time += rate) {\n        setTimeout(updateTitleStickyDirect, time);\n    }\n}\n\nfunction toggleTopSticky() {\n    var topBar = document.getElementById('top_nav_bar');\n    topBar.classList.remove('sticky_top');\n    if (document.getElementById('stickyNavigation').checked) {\n        topBar.classList.add('sticky_top');\n    }\n    updateTitleSticky();\n}\n\nfunction toggleLabelSticky() {\n    updateHash();\n    var table = document.getElementById('image_table');\n    table.classList.remove('nostickytable');\n    if (!document.getElementById('stickyLabels').checked) {\n        table.classList.add('nostickytable');\n    }\n}\n\nfunction removeGeneratedImages() {\n    document.getElementById('save_image_output').innerHTML = '';\n}\n\nfunction makeImage(minRow = 0, doClear = true) {\n    // Preprocess data\n    var imageTable = document.getElementById('image_table');\n    var rows = Array.from(imageTable.getElementsByTagName('tr')).filter(e => e.getElementsByTagName('img').length > 0);\n    var header = document.getElementById('image_table_header');\n    var headers = Array.from(header.getElementsByTagName('th')).slice(1);\n    var widest_width = 0;\n    var total_height = 0;\n    var columns = 0;\n    var rowData = [];\n    var pad_x = 64, pad_y = 64;\n    let count = 0;\n    let sizeMult = parseFloat(document.getElementById('makeimage_size').value.replaceAll('x', ''));\n    for (var row of rows) {\n        count++;\n        if (count < minRow) {\n            continue;\n        }\n        var images = Array.from(row.getElementsByTagName('img'));\n        var real_images = images.filter(i => i.src != 'placeholder.png');\n        widest_width = Math.max(widest_width, ...real_images.map(i => i.naturalWidth * sizeMult));\n        var height = Math.max(...real_images.map(i => i.naturalHeight * sizeMult));\n        var y = pad_y + total_height;\n        if (total_height + height > 30000) { // 32,767 is max canvas size\n            setTimeout(() => makeImage(count, false), 100);\n            break;\n        }\n        total_height += height + 1;\n        columns = Math.max(columns, images.length);\n        var label = row.getElementsByClassName('axis_label_td')[0];\n        rowData.push({ row, images, real_images, height, label, y });\n    }\n    var holder = document.getElementById('save_image_output');\n    if (doClear) {\n        removeGeneratedImages();\n    }\n    // Temporary canvas to measure what padding we need\n    var canvas = new OffscreenCanvas(256, 256);\n    var ctx = canvas.getContext('2d');\n    ctx.beginPath();\n    ctx.rect(0, 0, canvas.width, canvas.height);\n    ctx.font = '16px sans';\n    ctx.textBaseline = 'top';\n    for (var row of rowData) {\n        var blocks = row.label.getElementsByTagName('b');\n        pad_x = Math.max(pad_x, ctx.measureText(blocks[0].textContent).width);\n        if (blocks.length == 2) {\n            pad_x = Math.max(pad_x, ctx.measureText(blocks[1].textContent).width);\n        }\n    }\n    pad_x = Math.min(pad_x, widest_width / 2);\n    pad_x += 5;\n    canvas = document.createElement('canvas');\n    canvas.width = (widest_width + 1) * columns + pad_x;\n    canvas.height = total_height + pad_y;\n    ctx = canvas.getContext('2d');\n    // Background\n    ctx.beginPath();\n    ctx.rect(0, 0, canvas.width, canvas.height);\n    ctx.fillStyle = '#202020';\n    ctx.fill();\n    // Secondary color toggling\n    var doColor = false;\n    ctx.fillStyle = '#303030';\n    var grid_x = pad_x;\n    for (var part of headers) {\n        if (part.getElementsByTagName('b').length == 2) {\n            doColor = !doColor;\n        }\n        if (doColor) {\n            ctx.beginPath();\n            ctx.rect(grid_x, 0, widest_width, pad_y);\n            ctx.fill();\n        }\n        grid_x += widest_width + 1;\n    }\n    doColor = false;\n    for (var row of rowData) {\n        if (row.label.getElementsByTagName('b').length == 2) {\n            doColor = !doColor;\n        }\n        if (doColor) {\n            ctx.beginPath();\n            ctx.rect(0, row.y, pad_x, row.height);\n            ctx.fill();\n        }\n    }\n    // Grid lines\n    ctx.fillStyle = '#000000';\n    for (var row of rowData) {\n        ctx.beginPath();\n        ctx.rect(0, row.y, canvas.width, 1);\n        ctx.fill();\n    }\n    grid_x = pad_x - 1;\n    for (var i = 0; i < columns; i++) {\n        ctx.beginPath();\n        ctx.rect(grid_x, 0, 1, canvas.height);\n        ctx.fill();\n        grid_x += widest_width + 1;\n    }\n    // Text Labels\n    ctx.font = '16px sans';\n    ctx.textBaseline = 'top';\n    ctx.fillStyle = '#ffffff';\n    ctx.beginPath();\n    ctx.rect(0, 0, canvas.width, canvas.height);\n    grid_x = pad_x + 5;\n    for (var part of headers) {\n        var blocks = part.getElementsByTagName('b');\n        if (blocks.length == 2) {\n            ctx.fillText(blocks[0].textContent, grid_x, 5, widest_width);\n            ctx.fillText(blocks[1].textContent, grid_x, 25, widest_width);\n        }\n        else {\n            ctx.fillText(blocks[0].textContent, grid_x, 25, widest_width);\n        }\n        grid_x += widest_width + 1;\n    }\n    function wrap(text, width) {\n        var words = text.split(' ');\n        var lines = [];\n        var line = '';\n        for (var word of words) {\n            var newLine = line + word + ' ';\n            if (ctx.measureText(newLine).width > width) {\n                lines.push(line);\n                line = word + ' ';\n            }\n            else {\n                line = newLine;\n            }\n        }\n        lines.push(line);\n        return lines.join('\\n');\n    }\n    function writeMultiline(ctx, text, x, y) {\n        for (var line of text.split('\\n')) {\n            ctx.fillText(line, x, y);\n            y += 16;\n        }\n    }\n    for (var row of rowData) {\n        var blocks = row.label.getElementsByTagName('b');\n        if (blocks.length == 2) {\n            writeMultiline(ctx, wrap(blocks[0].textContent + \"\\n\" + blocks[1].textContent, widest_width / 2), 5, row.y + 4);\n        }\n        else {\n            writeMultiline(ctx, wrap(blocks[0].textContent, widest_width / 2), 5, row.y + 25);\n        }\n    }\n    // Images\n    for (var row of rowData) {\n        var x = pad_x;\n        for (var image of row.images) {\n            if (image.src != 'placeholder.png') {\n                ctx.drawImage(image, x, row.y, image.naturalWidth * sizeMult, image.naturalHeight * sizeMult);\n                x += widest_width + 1;\n            }\n        }\n    }\n    var imageType = document.getElementById('makeimage_type').value;\n    try {\n        var data = canvas.toDataURL(`image/${imageType}`);\n        canvas.remove();\n        var img = new Image();\n        img.className = 'save_image_output_img';\n        img.src = data;\n        holder.appendChild(img);\n    }\n    catch (e) {\n        holder.appendChild(canvas);\n        canvas.className = 'save_image_output_img';\n        canvas.style.width = \"200px\";\n        canvas.style.height = \"200px\";\n    }\n    $('#save_image_output_modal').modal('show');\n}\n\nfunction makeGif() {\n    let holder = document.getElementById('save_image_output');\n    removeGeneratedImages();\n    let axisId = document.getElementById('makegif_axis').value;\n    if (axisId == 'x-axis') {\n        axisId = getCurrentSelectedAxis('x');\n    }\n    let sizeMult = parseFloat(document.getElementById('makegif_size').value.replaceAll('x', ''));\n    let speed = parseFloat(document.getElementById('makegif_speed').value.replaceAll('/s', ''));\n    let axis = getAxisById(axisId);\n    let images = [];\n    let imgPath = [];\n    let index = 0;\n    for (let subAxis of rawData.axes) {\n        if (subAxis.id == axisId) {\n            index = imgPath.length;\n            imgPath.push(null);\n        }\n        else {\n            imgPath.push(getSelectedValKey(subAxis));\n        }\n    }\n    for (let val of axis.values) {\n        if (!canShowVal(axis.id, val.key)) {\n            continue;\n        }\n        imgPath[index] = val.path;\n        let slashed = imgPath.join('/');\n        let actualUrl = slashed + '.' + getExtension(slashed);\n        images.push(actualUrl);\n    }\n    if (document.getElementById('makegif_direction').value == 'Backwards') {\n        images.reverse();\n    }\n    let encoder = new GIFEncoder();\n    encoder.setRepeat(0);\n    encoder.setDelay(1000 / speed);\n    encoder.start();\n    let image1 = new Image();\n    image1.src = images[0];\n    image1.decode().then(() => {\n        let canvas = document.createElement('canvas');\n        canvas.width = image1.naturalWidth * sizeMult;\n        canvas.height = image1.naturalHeight * sizeMult;\n        ctx = canvas.getContext('2d');\n        ctx.beginPath();\n        let id = 1;\n        let image2 = new Image();\n        let callback = () => {\n            ctx.drawImage(image2, 0, 0, canvas.width, canvas.height);\n            encoder.addFrame(ctx);\n            if (id >= images.length) {\n                encoder.finish();\n                let binary_gif = encoder.stream().getData();\n                let data_url = 'data:image/gif;base64,' + encode64(binary_gif);\n                let animatedImage = document.createElement('img');\n                animatedImage.className = 'save_image_output_img';\n                animatedImage.src = data_url;\n                image1.remove();\n                image2.remove();\n                holder.appendChild(animatedImage);\n                $('#save_image_output_modal').modal('show');\n            }\n            else {\n                image2 = new Image();\n                image2.src = images[id];\n                id++;\n                image2.decode().then(callback);\n            }\n        };\n        image2.src = images[0];\n        image2.decode().then(callback);\n    });\n\n}\n\nfunction updateHash() {\n    var hash = `#auto-loc`;\n    for (let elem of ['showDescriptions', 'autoScaleImages', 'stickyNavigation', 'stickyLabels']) {\n        hash += `,${document.getElementById(elem).checked}`;\n    }\n    for (let val of ['x', 'y', 'x2', 'y2']) {\n        hash += `,${encodeURIComponent(getCurrentSelectedAxis(val))}`;\n    }\n    for (let subAxis of rawData.axes) {\n        hash += `,${encodeURIComponent(getSelectedValKey(subAxis))}`;\n    }\n    for (let axis of rawData.axes) {\n        for (let value of axis.values) {\n            if (!canShowVal(axis.id, value.key)) {\n                hash += `&hide=${encodeURIComponent(axis.id)},${encodeURIComponent(value.key)}`;\n            }\n        }\n    }\n    history.pushState(null, null, hash);\n}\n\nfunction applyHash(hash) {\n    if (!hash) {\n        return;\n    }\n    let params = hash.substring(1).split('&');\n    for (let hidden of params.slice(1)) {\n        let [action, value] = hidden.split('=');\n        if (action == 'hide') {\n            let [axis, val] = value.split(',');\n            setShowVal(axis, val, false);\n        }\n    }\n    let hashInputs = params[0].split(',');\n    let expectedLen = 1 + 4 + 4 + rawData.axes.length;\n    if (hashInputs.length != expectedLen) {\n        console.log(`Hash length mismatch: ${hashInputs.length} != ${expectedLen}, skipping value reload.`);\n        return;\n    }\n    if (hashInputs[0] != 'auto-loc') {\n        console.log(`Hash prefix mismatch: ${hashInputs[0]} != auto-loc, skipping value reload.`);\n        return;\n    }\n    let index = 1;\n    for (let elem of ['showDescriptions', 'autoScaleImages', 'stickyNavigation', 'stickyLabels']) {\n        document.getElementById(elem).checked = hashInputs[index++] == 'true';\n    }\n    for (let axis of ['x', 'y', 'x2', 'y2']) {\n        let id = axis + '_' + decodeURIComponent(hashInputs[index++]);\n        let target = document.getElementById(id);\n        if (!target) {\n            console.log(`Axis element not found: ${id}, skipping value reload.`);\n            return;\n        }\n        target.click();\n    }\n    for (let subAxis of rawData.axes) {\n        let val = decodeURIComponent(hashInputs[index++]);\n        let target = getNavValTab(subAxis.id, val);\n        if (!target) {\n            console.log(`Axis-value element not found: ${id}, skipping value reload.`);\n            return;\n        }\n        target.click();\n    }\n    updateStylesToMatchInputs();\n}\n\nlet lastUpdateObj = null;\nlet updateCheckCount = 0;\nlet updatesWithoutData = 0;\n\nfunction tryReloadImg(img) {\n    let target = img.dataset.errored_src;\n    delete img.dataset.errored_src;\n    img.removeAttribute('width');\n    img.removeAttribute('height');\n    img.addEventListener('error', function() {\n        setImgPlaceholder(img);\n    });\n    img.src = target;\n    if (typeof getMetadataScriptFor != 'undefined') {\n        let newScr = document.createElement('script');\n        newScr.src = getMetadataScriptFor(img.dataset.img_path);\n        document.getElementById('image_script_dump').appendChild(newScr);\n    }\n}\n\nfunction checkForUpdates() {\n    if (!window.lastUpdated) {\n        if (updatesWithoutData++ > 2) {\n            console.log('Update-checker has no more updates.');\n            for (let img of document.querySelectorAll(`img[data-errored_src]`)) {\n                tryReloadImg(img);\n            }\n            return;\n        }\n    }\n    else {\n        console.log(`Update-checker found ${window.lastUpdated.length} updates.`);\n        for (let url of window.lastUpdated) {\n            for (let img of document.querySelectorAll(`img[data-errored_src]`)) {\n                if (img.dataset.errored_src.endsWith(url)) {\n                    tryReloadImg(img);\n                }\n            }\n        }\n        updateScaling();\n        window.lastUpdated = null;\n    }\n    if (lastUpdateObj != null) {\n        lastUpdateObj.remove();\n    }\n    lastUpdateObj = document.createElement('script');\n    lastUpdateObj.src = `last.js?vary=${updateCheckCount++}`;\n    document.body.appendChild(lastUpdateObj);\n    setTimeout(checkForUpdates, 5 * 1000);\n}\n\nloadData();\n"
  },
  {
    "path": "assets/styles.css",
    "content": "/*\n If you want to customize your stylesheet, please edit 'styles-user.css' instead of this.\n*/\n\n.sel_table tr td {\n    border: 1px solid black;\n    padding-right: 16px;\n    padding-left: 16px;\n}\n.sel_table {\n    min-width: 60em;\n    width: 100%;\n}\n.secondary {\n    background-color: #202020;\n}\n.emptytab {\n    width: 0px;\n}\n.primary {\n    background-color: #303030;\n}\n.axis_table_cell {\n    width: calc(min(40em, max(10em, 100vw - 40em)));\n    max-height: 8em;\n    overflow: auto;\n}\n.tabval_subdiv {\n    min-width: calc(100vw - 5em - min(40em, max(10em, 100vw - 40em)));\n    max-height: 8em;\n    overflow: auto;\n}\ntable tr td,\ntable tr th {\n    vertical-align: top;\n    border: 1px solid black;\n    word-break: break-all;\n}\nth {\n    position: sticky;\n    top: -1px;\n    background-color: #202020;\n    background-clip: padding-box;\n}\ntable tr td:first-child {\n    position: sticky;\n    left: -1px;\n}\n.nostickytable tr:first-child {\n    position: static !important;\n}\n.nostickytable tr th {\n    position: static !important;\n}\n.nostickytable tr td:first-child {\n    position: static !important;\n}\n.popup_modal_background {\n    font-family: monospace, monospace;\n    background-color: rgb(50, 50, 50, 0.7);\n    text-align: center;\n}\n.popup_modal_img {\n    height: 100%;\n    width: 100%;\n    max-height: calc(min(100vw, 100vh - 8em));\n    max-width: 90vw;\n    position: relative;\n    margin: auto;\n    object-fit: contain;\n}\n.popup_modal_undertext {\n    background-color: #404060;\n    overflow-wrap: break-word;\n}\n.modal_inner_div {\n    max-width: 90vw;\n    margin: auto;\n}\n.advanced_settings_section {\n    max-width: calc(max(1500px, 90em));\n    text-align: left;\n    margin: auto;\n}\n.timer_range {\n    vertical-align: bottom;\n}\n.tab_hidden {\n    display: none;\n}\n.nav-link:focus {\n    background-color: #909050 !important;\n}\n.axis_label_td {\n    left: 0px;\n    background-color: #202020;\n    background-clip: padding-box;\n    word-break: break-all;\n    min-width: 10em;\n}\n.superaxis_second {\n    background-color: #303030;\n}\n.axis_selectors {\n    text-align: right;\n    margin: auto;\n    width: fit-content;\n}\n.sticky_top {\n    position: sticky;\n    top: 0;\n}\n.accordion-button {\n    padding: 0.5rem;\n}\n.save_image_area {\n    text-align: center;\n}\n.save_image_area img {\n    margin-right: 1rem;\n    margin-left: 1rem;\n    border: 2px solid orange;\n    border-radius: 0.5rem;\n}\n.content_box {\n    display: inline-block;\n}\n.top_nav_bar {\n    position: sticky;\n    left: 2.5vw;\n    width: 95vw;\n}\n.image_table_box {\n    display: inline-block;\n    min-width: 100%;\n}\n.image_table {\n    margin: auto;\n} \n.save_image_output {\n    text-align: center;\n}\n.save_image_output_img {\n    max-width: 100%;\n    max-height: 70vh;\n}\n.advanced-checkbox {\n    display: inline-block;\n    border-radius: 0.2rem;\n    border: 1px dashed rgba(255, 255, 255, 0.25);\n    margin: 0.1rem;\n}\nlabel {\n    display: inline;\n}\n"
  },
  {
    "path": "gridgencore.py",
    "content": "# This file is part of Infinity Grid Generator, view the README.md at https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script for more information.\n\nimport os, glob, yaml, json, shutil, math, re, time\nfrom copy import copy\nfrom PIL import Image\nfrom git import Repo\n\n######################### Core Variables #########################\n\nASSET_DIR = os.path.dirname(__file__) + \"/assets\"\nEXTRA_FOOTER = \"...\"\nEXTRA_ASSETS = []\nVERSION = None\nvalid_modes = {}\nIMAGES_CACHE = None\n\n######################### Hooks #########################\n\n# hook(SingleGridCall)\ngrid_call_init_hook: callable = None\n# hook(SingleGridCall, param_name: str, value: any) -> bool\ngrid_call_param_add_hook: callable = None\n# hook(SingleGridCall, param_name: str, dry: bool)\ngrid_call_apply_hook: callable = None\n# hook(GridRunner)\ngrid_runner_pre_run_hook: callable = None\n# hook(GridRunner)\ngrid_runner_pre_dry_hook: callable = None\n# hook(GridRunner, PassThroughObject, set: SingleGridCall) -> ResultObject\ngrid_runner_post_dry_hook: callable = None\n# hook(GridRunner, SingleGridCall) -> int\ngrid_runner_count_steps: callable = None\n# hook(PassThroughObject) -> dict\nwebdata_get_base_param_data: callable = None\n\n######################### Utilities #########################\n\ndef escape_html(text: str):\n    return str(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\"', '&quot;')\n\ndef clean_file_path(fn: str):\n    fn = fn.replace('\\\\', '/')\n    while '//' in fn:\n        fn = fn.replace('//', '/')\n    return fn\n\ndef get_version():\n    global VERSION\n    if VERSION is not None:\n        return VERSION\n    try:\n        repo = Repo(os.path.dirname(__file__))\n        VERSION = repo.head.commit.hexsha[:8]\n    except Exception:\n        VERSION = \"Unknown\"\n    return VERSION\n\ndef list_image_files():\n    global IMAGES_CACHE\n    if IMAGES_CACHE is not None:\n        return IMAGES_CACHE\n    image_dir = clean_file_path(ASSET_DIR + \"/images\")\n    IMAGES_CACHE = list()\n    for path, _, files in os.walk(image_dir):\n        for name in files:\n            _, ext = os.path.splitext(name)\n            if ext in [\".jpg\", \".png\", \".webp\"]:\n                fn = path + \"/\" + name\n                fn = clean_file_path(fn).replace(image_dir, '')\n                while fn.startswith('/'):\n                    fn = fn[1:]\n                IMAGES_CACHE.append(fn)\n    return IMAGES_CACHE\n\ndef clear_caches():\n    global IMAGES_CACHE\n    IMAGES_CACHE = None\n\ndef get_name_list():\n    file_list = glob.glob(ASSET_DIR + \"/*.yml\")\n    just_file_names = sorted(list(map(lambda f: os.path.relpath(f, ASSET_DIR), file_list)))\n    return just_file_names\n\ndef fix_dict(d: dict):\n    if d is None:\n        return None\n    if type(d) is not dict:\n        raise RuntimeError(f\"Value '{d}' is supposed to be submapping but isn't (it's plaintext, a list, or some other incorrect format). Did you typo the formatting?\")\n    return {str(k).lower(): v for k, v in d.items()}\n\ndef clean_for_web(text: str):\n    if text is None:\n        return None\n    if type(text) is not str:\n        raise RuntimeError(f\"Value '{text}' is supposed to be text but isn't (it's a datamapping, list, or some other incorrect format). Did you typo the formatting?\")\n    return text.replace('\"', '&quot;')\n\ndef clean_id(id: str):\n    return re.sub(\"[^a-z0-9]\", \"_\", id.lower().strip())\n\ndef clean_mode(id: str):\n    return re.sub(\"[^a-z]\", \"\", id.lower().strip())\n\ndef clean_name(name: str):\n    return str(name).lower().replace(' ', '').replace('[', '').replace(']', '').strip()\n\ndef get_best_in_list(name: str, list: list):\n    backup = None\n    best_len = 999\n    name = clean_name(name)\n    for list_val in list:\n        list_val_clean = clean_name(list_val)\n        if list_val_clean == name:\n            return list_val\n        if name in list_val_clean:\n            if len(list_val_clean) < best_len:\n                backup = list_val\n                best_len = len(list_val_clean)\n    return backup\n\ndef choose_better_file_name(raw_name: str, full_name: str):\n    partial_name = os.path.splitext(os.path.basename(full_name))[0]\n    if '/' in raw_name or '\\\\' in raw_name or '.' in raw_name or len(raw_name) >= len(partial_name):\n        return raw_name\n    return partial_name\n\ndef fix_num(num):\n    if num is None or math.isinf(num) or math.isnan(num):\n        return None\n    return num\n\ndef expand_numeric_list_ranges(in_list, num_type):\n    out_list = list()\n    for i in range(0, len(in_list)):\n        raw_val = str(in_list[i]).strip()\n        if raw_val in [\"..\", \"...\", \"....\"]:\n            if i < 2 or i + 1 >= len(in_list):\n                raise RuntimeError(f\"Cannot use ellipses notation at index {i}/{len(in_list)} - must have at least 2 values before and 1 after.\")\n            prior = out_list[-1]\n            double_prior = out_list[-2]\n            after = num_type(in_list[i + 1])\n            step = prior - double_prior\n            if (step < 0) != ((after - prior) < 0):\n                raise RuntimeError(f\"Ellipses notation failed for step {step} between {prior} and {after} - steps backwards.\")\n            count = int((after - prior) / step)\n            for x in range(1, count):\n                out_list.append(prior + x * step)\n        else:\n            out_list.append(num_type(raw_val))\n    return out_list\n\n######################### Value Modes #########################\n\nclass GridSettingMode:\n    \"\"\"\n    Defines a custom parameter input mode for an Infinity Grid Generator.\n    'dry' is True if the mode should be processed in dry runs, or False if it should be skipped.\n    'type' is 'text', 'integer', 'decimal', or 'boolean'\n    'apply' is a function to call taking (passthroughObject, value)\n    'min' is for integer/decimal type, optional minimum value\n    'max' is for integer/decimal type, optional maximum value\n    'valid_list' is for text type, an optional lambda that returns a list of valid values\n    'clean' is an optional function to call that takes (passthroughObject, value) and returns a cleaned copy of the value, or raises an error if invalid\n    'parse_list' is an optional function to call that takes a List and returns a List, to apply any special pre-processing for list-format inputs.\n    \"\"\"\n    def __init__(self, dry: bool, type: str, apply: callable, min: float = None, max: float = None, valid_list: callable = None, clean: callable = None, parse_list: callable = None):\n        self.dry = dry\n        self.type = type\n        self.apply = apply\n        self.min = min\n        self.max = max\n        self.clean = clean\n        self.valid_list = valid_list\n        self.parse_list = parse_list\n\ndef registerMode(name: str, mode: GridSettingMode):\n    mode.name = name\n    valid_modes[clean_name(name)] = mode\n\n######################### Validation #########################\n\ndef validate_params(grid, params: dict):\n    for p,v in params.items():\n        params[p] = validate_single_param(p, grid.proc_variables(v))\n\ndef apply_field(name: str):\n    def applier(p, v):\n        setattr(p, name, v)\n    return applier\n\ndef apply_field_as_image_data(name: str):\n    def applier(p, v):\n        file_name = get_best_in_list(v, list_image_files())\n        if file_name is None:\n            raise RuntimeError(\"Invalid parameter '{p}' as '{v}': image file does not exist\")\n        path = ASSET_DIR + \"/images/\" + file_name\n        image = Image.open(path)\n        setattr(p, name, image)\n    return applier\n\ndef validate_single_param(p: str, v):\n    orig_v = v\n    p = clean_mode(p)\n    mode = valid_modes.get(p)\n    if mode is None:\n        raise RuntimeError(f\"Invalid grid parameter '{p}': unknown mode\")\n    mode_type = mode.type\n    if mode_type == \"integer\":\n        v_int = int(v)\n        if v_int is None:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must be an integer number\")\n        min = mode.min\n        max = mode.max\n        if min is not None and v_int < min:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must be at least {min}\")\n        if max is not None and v_int > max:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must not exceed {max}\")\n        v = v_int\n    elif mode_type == \"decimal\":\n        v_float = float(v)\n        if v_float is None:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must be a decimal number\")\n        min = mode.min\n        max = mode.max\n        if min is not None and v_float < min:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must be at least {min}\")\n        if max is not None and v_float > max:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must not exceed {max}\")\n        v = v_float\n    elif mode_type == \"boolean\":\n        v_clean = str(v).lower().strip()\n        if v_clean == \"true\":\n            v = True\n        elif v_clean == \"false\":\n            v = False\n        else:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': must be either 'true' or 'false'\")\n    elif mode_type == \"text\" and mode.valid_list is not None:\n        valid_list = mode.valid_list()\n        v = get_best_in_list(clean_name(v), valid_list)\n        if v is None:\n            raise RuntimeError(f\"Invalid parameter '{p}' as '{orig_v}': not matched to any entry in list {list(valid_list)}\")\n    if mode.clean is not None:\n        return mode.clean(p, v)\n    return v\n\n######################### YAML Parsing and Processing #########################\n\nclass GridYamlLoader(yaml.SafeLoader):\n    pass\n\ntry:\n    from yamlinclude import YamlIncludeConstructor\n    YamlIncludeConstructor.add_to_loader_class(loader_class=GridYamlLoader, base_dir=ASSET_DIR)\nexcept:\n    from yaml_include import Constructor\n    yaml.add_constructor(\"!include\", Constructor(base_dir=ASSET_DIR), GridYamlLoader)\n\nclass AxisValue:\n    def __init__(self, axis, grid, key: str, val):\n        self.axis = axis\n        self.key = clean_id(str(key))\n        if any(x.key == self.key for x in axis.values):\n            self.key += f\"__{len(axis.values)}\"\n        self.params = list()\n        if isinstance(val, str):\n            halves = val.split('=', maxsplit=1)\n            if len(halves) != 2:\n                raise RuntimeError(f\"Invalid value '{key}': '{val}': not expected format\")\n            self.skip = False\n            halves[0] = grid.proc_variables(halves[0])\n            halves[1] = grid.proc_variables(halves[1])\n            try:\n                halves[1] = validate_single_param(halves[0], halves[1])\n            except RuntimeError:\n                if grid.skip_invalid:\n                    self.skip = True\n                else:\n                    raise\n            self.title = halves[1]\n            self.params = { clean_mode(halves[0]): halves[1] }\n            self.description = None\n            self.show = True\n            self.path = clean_name(self.key)\n        else:\n            self.title = grid.proc_variables(val.get(\"title\"))\n            self.description = grid.proc_variables(val.get(\"description\"))\n            self.skip = (str(grid.proc_variables(val.get(\"skip\")))).lower() == \"true\"\n            self.params = fix_dict(val.get(\"params\"))\n            self.show = (str(grid.proc_variables(val.get(\"show\")))).lower() != \"false\"\n            self.path = str(val.get(\"path\") or clean_name(self.key))\n            if self.title is None or self.params is None:\n                raise RuntimeError(f\"Invalid value '{key}': '{val}': missing title or params\")\n            if not self.skip:\n                try:\n                    validate_params(grid, self.params)\n                except RuntimeError:\n                    if grid.skip_invalid:\n                        self.skip = True\n                    else:\n                        raise\n    \n    def __str__(self):\n        return f\"(title={self.title}, description={self.description}, params={self.params})\"\n    def __unicode__(self):\n        return self.__str__()\n\nclass Axis:\n    def build_from_list_str(self, id, grid, list_str):\n        is_split_by_double_pipe = \"||\" in list_str\n        values_list = list_str.split(\"||\" if is_split_by_double_pipe else \",\")\n        self.mode_name = clean_name(str(id))\n        self.mode = valid_modes.get(clean_mode(self.mode_name))\n        if self.mode is None:\n            raise RuntimeError(f\"Invalid axis mode '{self.mode}' from '{id}': unknown mode\")\n        if self.mode.type == \"integer\":\n            values_list = expand_numeric_list_ranges(values_list, int)\n        elif self.mode.type == \"decimal\":\n            values_list = expand_numeric_list_ranges(values_list, float)\n        index = 0\n        if self.mode.parse_list is not None:\n            values_list = self.mode.parse_list(values_list)\n        for val in values_list:\n            try:\n                if isinstance(val, dict):\n                    self.values.append(AxisValue(self, grid, str(index), val))\n                    continue\n                val = str(val).strip()\n                index += 1\n                if is_split_by_double_pipe and val == \"\" and index == len(values_list):\n                    continue\n                self.values.append(AxisValue(self, grid, str(index), f\"{id}={val}\"))\n            except Exception as e:\n                raise RuntimeError(f\"value '{val}' errored: {e}\")\n\n    def __init__(self, grid, id: str, obj):\n        self.raw_id = id\n        self.values = list()\n        self.id = clean_id(str(id))\n        if any(x.id == self.id for x in grid.axes):\n            self.id += f\"__{len(grid.axes)}\"\n        if isinstance(obj, str):\n            self.title = id\n            self.default = None\n            self.description = \"\"\n            self.build_from_list_str(id, grid, obj)\n        else:\n            self.title = grid.proc_variables(obj.get(\"title\"))\n            self.default = grid.proc_variables(obj.get(\"default\"))\n            if self.title is None:\n                raise RuntimeError(\"missing title\")\n            self.description = grid.proc_variables(obj.get(\"description\"))\n            values_obj = obj.get(\"values\")\n            if values_obj is None:\n                raise RuntimeError(\"missing values\")\n            elif isinstance(values_obj, str):\n                self.build_from_list_str(id, grid, values_obj)\n            else:\n                for key, val in values_obj.items():\n                    try:\n                        self.values.append(AxisValue(self, grid, key, val))\n                    except Exception as e:\n                        raise RuntimeError(f\"value '{key}' errored: {e}\")\n\nclass GridFileHelper:\n    def proc_variables(self, text):\n        if text is None:\n            return None\n        text = str(text)\n        for key, val in self.variables.items():\n            text = text.replace(key, val)\n        return text\n    \n    def read_grid_direct(self, key: str):\n        return self.grid_obj.get(key)\n    \n    def read_str_from_grid(self, key: str):\n        return self.proc_variables(self.read_grid_direct(key))\n\n    def parse_yaml(self, yaml_content: dict, grid_file: str):\n        self.variables = dict()\n        self.axes = list()\n        yaml_content = fix_dict(yaml_content)\n        vars_obj = fix_dict(yaml_content.get(\"variables\"))\n        if vars_obj is not None:\n            for key, val in vars_obj.items():\n                self.variables[str(key).lower()] = str(val)\n        self.grid_obj = fix_dict(yaml_content.get(\"grid\"))\n        if self.grid_obj is None:\n            raise RuntimeError(f\"Invalid file {grid_file}: missing basic 'grid' root key\")\n        self.title = self.read_str_from_grid(\"title\")\n        self.description = self.read_str_from_grid(\"description\")\n        self.stylesheet = self.read_str_from_grid(\"stylesheet\") or ''\n        self.author = self.read_str_from_grid(\"author\")\n        self.format = self.read_str_from_grid(\"format\")\n        self.out_path = self.grid_obj.get(\"outpath\")\n        self.skip_invalid = self.read_grid_direct(\"skip_invalid\") or getattr(self, 'skip_invalid', False)\n        if self.title is None or self.description is None or self.author is None or self.format is None:\n            raise RuntimeError(f\"Invalid file {grid_file}: missing grid title, author, format, or description in grid obj {self.grid_obj}\")\n        self.params = fix_dict(self.grid_obj.get(\"params\"))\n        if self.params is not None:\n            validate_params(self, self.params)\n        axes_obj = fix_dict(yaml_content.get(\"axes\"))\n        if axes_obj is None:\n            raise RuntimeError(f\"Invalid file {grid_file}: missing basic 'axes' root key\")\n        for id, axis_obj in axes_obj.items():\n            try:\n                self.axes.append(Axis(self, id, axis_obj if isinstance(axis_obj, str) else fix_dict(axis_obj)))\n            except Exception as e:\n                raise RuntimeError(f\"Invalid axis '{id}': errored: {e}\")\n        total_count = 1\n        for axis in self.axes:\n            total_count *= len(axis.values)\n        if total_count <= 0:\n            raise RuntimeError(f\"Invalid file {grid_file}: something went wrong ... is an axis empty? total count is {total_count} for {len(self.axes)} axes\")\n        clean_desc = self.description.replace('\\n', ' ')\n        print(f\"Loaded grid file, title '{self.title}', description '{clean_desc}', with {len(self.axes)} axes... combines to {total_count} total images\")\n        return self\n\n######################### Actual Execution Logic #########################\n\nclass SingleGridCall:\n    def __init__(self, values: list):\n        self.values = values\n        self.skip = False\n        for val in values:\n            if val.skip:\n                self.skip = True\n        if grid_call_init_hook is not None:\n            grid_call_init_hook(self)\n\n    def flatten_params(self, grid: GridFileHelper):\n        self.grid = grid\n        self.params = grid.params.copy() if grid.params is not None else dict()\n        for val in self.values:\n            for p, v in val.params.items():\n                if grid_call_param_add_hook is None or not grid_call_param_add_hook(self, p, v):\n                    self.params[p] = v\n\n    def apply_to(self, p, dry: bool):\n        for name, val in self.params.items():\n            mode = valid_modes[clean_mode(name)]\n            if not dry or mode.dry:\n                mode.apply(p, val)\n        if grid_call_apply_hook is not None:\n            grid_call_apply_hook(self, p, dry)\n\nclass GridRunner:\n    def __init__(self, grid: GridFileHelper, do_overwrite: bool, base_path: str, p, fast_skip: bool):\n        self.grid = grid\n        self.total_run = 0\n        self.total_skip = 0\n        self.total_steps = 0\n        self.do_overwrite = do_overwrite\n        self.base_path = base_path\n        self.fast_skip = fast_skip\n        self.p = p\n        grid.min_width = None\n        grid.min_height = None\n        grid.initial_p = p\n        self.last_update = []\n\n    def update_live_file(self, new_file: str):\n        t_now = time.time()\n        self.last_update = [x for x in self.last_update if t_now - x['t'] < 20]\n        self.last_update.append({'f': new_file, 't': t_now})\n        with open(self.base_path + '/last.js', 'w', encoding=\"utf-8\") as f:\n            update_str = '\", \"'.join([x['f'] for x in self.last_update])\n            f.write(f'window.lastUpdated = [\"{update_str}\"]')\n\n    def build_value_set_list(self, axis_list: list):\n        result = list()\n        if len(axis_list) == 0:\n            return result\n        cur_axis = axis_list[0]\n        if len(axis_list) == 1:\n            for val in cur_axis.values:\n                if not val.skip or not self.fast_skip:\n                    new_list = list()\n                    new_list.append(val)\n                    result.append(SingleGridCall(new_list))\n            return result\n        next_axis_list = axis_list[1::]\n        for obj in self.build_value_set_list(next_axis_list):\n            for val in cur_axis.values:\n                if not val.skip or not self.fast_skip:\n                    new_list = obj.values.copy()\n                    new_list.append(val)\n                    result.append(SingleGridCall(new_list))\n        return result\n\n    def preprocess(self):\n        self.value_sets = self.build_value_set_list(list(reversed(self.grid.axes)))\n        print(f'Have {len(self.value_sets)} unique value sets, will go into {self.base_path}')\n        for set in self.value_sets:\n            set.filepath = self.base_path + '/' + '/'.join(list(map(lambda v: v.path, set.values)))\n            set.data = ', '.join(list(map(lambda v: f\"{v.axis.title}={v.title}\", set.values)))\n            set.flatten_params(self.grid)\n            set.do_skip = set.skip or (not self.do_overwrite and os.path.exists(set.filepath + \".\" + self.grid.format))\n            if set.do_skip:\n                self.total_skip += 1\n            else:\n                self.total_run += 1\n                self.total_steps += grid_runner_count_steps(self, set) if grid_runner_count_steps is not None else 1\n        print(f\"Skipped {self.total_skip} files, will run {self.total_run} files, for {self.total_steps} total steps\")\n\n    def run(self, dry: bool):\n        if grid_runner_pre_run_hook is not None:\n            grid_runner_pre_run_hook(self)\n        iteration = 0\n        last = None\n        for set in self.value_sets:\n            if set.do_skip:\n                continue\n            iteration += 1\n            if not dry:\n                print(f'On {iteration}/{self.total_run} ... Set: {set.data}, file {set.filepath}')\n            p = copy(self.p)\n            if grid_runner_pre_dry_hook is not None:\n                grid_runner_pre_dry_hook(self)\n            set.apply_to(p, dry)\n            if dry:\n                continue\n            try:\n                last = grid_runner_post_dry_hook(self, p, set)\n            except FileNotFoundError as e:\n                if e.strerror == 'The filename or extension is too long' and hasattr(e, 'winerror') and e.winerror == 206:\n                    print(f\"\\n\\n\\nOS Error: {e.strerror} - see this article to fix that: https://www.autodesk.com/support/technical/article/caas/sfdcarticles/sfdcarticles/The-Windows-10-default-path-length-limitation-MAX-PATH-is-256-characters.html \\n\\n\\n\")\n                raise e\n            self.update_live_file(set.filepath + \".\" + self.grid.format)\n        return last\n\n######################### Web Data Builders #########################\n\nclass WebDataBuilder():\n    def build_json(grid: GridFileHelper, publish_gen_metadata: bool, p, dry_run: bool):\n        def get_axis(axis: str):\n            id = grid.read_str_from_grid(axis)\n            if id is None:\n                return ''\n            id = str(id).lower()\n            if id == 'none':\n                return 'none'\n            possible = [x.id for x in grid.axes if x.raw_id == id]\n            if len(possible) == 0:\n                raise RuntimeError(f\"Cannot find axis '{id}' for axis default '{axis}'... valid: {[x.raw_id for x in grid.axes]}\")\n            return possible[0]\n        show_descrip = grid.read_grid_direct('show descriptions')\n        result = {\n            'title': grid.title,\n            'description': grid.description,\n            'ext': grid.format,\n            'min_width': grid.min_width,\n            'min_height': grid.min_height,\n            'defaults': {\n                'show_descriptions': True if show_descrip is None else show_descrip,\n                'autoscale': grid.read_grid_direct('autoscale') or False,\n                'sticky': grid.read_grid_direct('sticky') or False,\n                'sticky_labels': grid.read_grid_direct('sticky labels') or False,\n                'x': get_axis('x axis'),\n                'y': get_axis('y axis'),\n                'x2': get_axis('x super axis'),\n                'y2': get_axis('y super axis')\n            }\n        }\n        if not dry_run:\n            result['will_run'] = True\n        if publish_gen_metadata:\n            result['metadata'] = None if webdata_get_base_param_data is None else webdata_get_base_param_data(p)\n        axes = list()\n        for axis in grid.axes:\n            j_axis = {\n                'id': str(axis.id).lower(),\n                'title': axis.title,\n                'description': axis.description or \"\"\n            }\n            exported_paths = {}\n            values = list()\n            for val in axis.values:\n                if val.path in exported_paths:\n                    continue\n                exported_paths[val.path] = val\n                j_val = {\n                    'key': str(val.key).lower(),\n                    'path': str(val.path),\n                    'title': val.title,\n                    'description': val.description or \"\",\n                    'show': val.show\n                }\n                if publish_gen_metadata:\n                    j_val['params'] = val.params\n                values.append(j_val)\n            j_axis['values'] = values\n            axes.append(j_axis)\n        result['axes'] = axes\n        return json.dumps(result)\n\n    def radio_button_html(name, id, descrip, label):\n        return f'<input type=\"radio\" class=\"btn-check\" name=\"{name}\" id=\"{str(id).lower()}\" autocomplete=\"off\" checked=\"\"><label class=\"btn btn-outline-primary\" for=\"{str(id).lower()}\" title=\"{descrip}\">{escape_html(label)}</label>\\n'\n\n    def axis_bar(label, content):\n        return f'<br><div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">{label}:&nbsp;\\n{content}</div>\\n'\n\n    def build_html(grid):\n        with open(ASSET_DIR + \"/page.html\", 'r', encoding=\"utf-8\") as reference_html:\n            html = reference_html.read()\n        x_select = \"\"\n        y_select = \"\"\n        x2Select = WebDataBuilder.radio_button_html('x2_axis_selector', f'x2_none', 'None', 'None')\n        y2Select = WebDataBuilder.radio_button_html('y2_axis_selector', f'y2_none', 'None', 'None')\n        content = '<div style=\"margin: auto; width: fit-content;\"><table class=\"sel_table\">\\n'\n        advanced_settings = ''\n        primary = True\n        for axis in grid.axes:\n            try:\n                axis_descrip = clean_for_web(axis.description or '')\n                tr_class = \"primary\" if primary else \"secondary\"\n                content += f'<tr class=\"{tr_class}\">\\n<td>\\n<h4>{escape_html(axis.title)}</h4>\\n'\n                advanced_settings += f'\\n<h4>{axis.title}</h4><div class=\"timer_box\">Auto cycle every <input style=\"width:30em;\" autocomplete=\"off\" type=\"range\" min=\"0\" max=\"360\" value=\"0\" class=\"form-range timer_range\" id=\"range_tablist_{axis.id}\"><label class=\"form-check-label\" for=\"range_tablist_{axis.id}\" id=\"label_range_tablist_{axis.id}\">0 seconds</label></div>\\nShow value: '\n                axis_class = \"axis_table_cell\"\n                if len(axis_descrip.strip()) == 0:\n                    axis_class += \" emptytab\"\n                content += f'<div class=\"{axis_class}\">{axis_descrip}</div></td>\\n<td><ul class=\"nav nav-tabs\" role=\"tablist\" id=\"tablist_{axis.id}\">\\n'\n                primary = not primary\n                is_first = axis.default is None\n                exported_paths = {}\n                for val in axis.values:\n                    if val.path in exported_paths:\n                        continue\n                    exported_paths[val.path] = val\n                    if axis.default is not None:\n                        is_first = str(axis.default) == str(val.key)\n                    selected = \"true\" if is_first else \"false\"\n                    active = \" active\" if is_first else \"\"\n                    is_first = False\n                    descrip = clean_for_web(val.description or '')\n                    content += f'<li class=\"nav-item\" role=\"presentation\"><a class=\"nav-link{active}\" data-bs-toggle=\"tab\" href=\"#tab_{axis.id}__{val.key}\" id=\"clicktab_{axis.id}__{val.key}\" aria-selected=\"{selected}\" role=\"tab\" title=\"{escape_html(val.title)}: {descrip}\">{escape_html(val.title)}</a></li>\\n'\n                    advanced_settings += f'&nbsp;<input class=\"form-check-input\" type=\"checkbox\" autocomplete=\"off\" id=\"showval_{axis.id}__{val.key}\" checked=\"true\" onchange=\"javascript:toggleShowVal(\\'{axis.id}\\', \\'{val.key}\\')\"> <label class=\"form-check-label\" for=\"showval_{axis.id}__{val.key}\" title=\"Uncheck this to hide \\'{escape_html(val.title)}\\' from the page.\">{escape_html(val.title)}</label>'\n                advanced_settings += f'&nbsp;&nbsp;<button class=\"submit\" onclick=\"javascript:toggleShowAllAxis(\\'{axis.id}\\')\">Toggle All</button>'\n                content += '</ul>\\n<div class=\"tab-content\">\\n'\n                is_first = axis.default is None\n                for val in axis.values:\n                    if axis.default is not None:\n                        is_first = str(axis.default) == str(val.key)\n                    active = \" active show\" if is_first else \"\"\n                    is_first = False\n                    descrip = clean_for_web(val.description or '')\n                    if len(descrip.strip()) == 0:\n                        active += \" emptytab\"\n                    content += f'<div class=\"tab-pane{active}\" id=\"tab_{axis.id}__{val.key}\" role=\"tabpanel\"><div class=\"tabval_subdiv\">{descrip}</div></div>\\n'\n            except Exception as e:\n                raise RuntimeError(f\"Failed to build HTML for axis '{axis.id}': {e}\")\n            content += '</div></td></tr>\\n'\n            x_select += WebDataBuilder.radio_button_html('x_axis_selector', f'x_{axis.id}', axis_descrip, axis.title)\n            y_select += WebDataBuilder.radio_button_html('y_axis_selector', f'y_{axis.id}', axis_descrip, axis.title)\n            x2Select += WebDataBuilder.radio_button_html('x2_axis_selector', f'x2_{axis.id}', axis_descrip, axis.title)\n            y2Select += WebDataBuilder.radio_button_html('y2_axis_selector', f'y2_{axis.id}', axis_descrip, axis.title)\n        content += '</table>\\n<div class=\"axis_selectors\">'\n        content += WebDataBuilder.axis_bar('X Axis', x_select)\n        content += WebDataBuilder.axis_bar('Y Axis', y_select)\n        content += WebDataBuilder.axis_bar('X Super-Axis', x2Select)\n        content += WebDataBuilder.axis_bar('Y Super-Axis', y2Select)\n        content += '</div></div>\\n'\n        html = html.replace(\"{TITLE}\", grid.title).replace(\"{CLEAN_DESCRIPTION}\", clean_for_web(grid.description)).replace(\"{DESCRIPTION}\", grid.description).replace(\"{CONTENT}\", content).replace(\"{ADVANCED_SETTINGS}\", advanced_settings).replace(\"{AUTHOR}\", grid.author).replace(\"{EXTRA_FOOTER}\", EXTRA_FOOTER).replace(\"{VERSION}\", get_version())\n        return html\n\n    def emit_web_data(path: str, grid, publish_gen_metadata: bool, p, yaml_content: dict, dry_run: bool):\n        print(\"Building final web data...\")\n        os.makedirs(path, exist_ok=True)\n        json = WebDataBuilder.build_json(grid, publish_gen_metadata, p, dry_run)\n        if not dry_run:\n            with open(path + '/last.js', 'w', encoding=\"utf-8\") as f:\n                f.write(\"window.lastUpdated = []\")\n        with open(path + \"/data.js\", 'w', encoding=\"utf-8\") as f:\n            f.write(\"rawData = \" + json)\n        with open(path + \"/config.yml\", 'w', encoding=\"utf-8\") as f:\n            yaml.dump(yaml_content, f, sort_keys=False, default_flow_style=False, width=1000)\n        for f in [\"bootstrap.min.css\", \"jsgif.js\", \"bootstrap.bundle.min.js\", \"proc.js\", \"jquery.min.js\", \"styles.css\", \"placeholder.png\"] + EXTRA_ASSETS:\n            shutil.copyfile(ASSET_DIR + \"/\" + f, path + \"/\" + f)\n        with open(ASSET_DIR + \"/styles-user.css\", 'r', encoding=\"utf-8\") as style:\n            with open(path + \"/styles-user.css\", 'w', encoding=\"utf-8\") as f:\n                f.write(style.read() + '\\n' + (grid.stylesheet or ''))\n        html = WebDataBuilder.build_html(grid)\n        with open(path + \"/index.html\", 'w', encoding=\"utf-8\") as f:\n            f.write(html)\n        print(f\"Web file is now at {path}/index.html\")\n        return json\n\n######################### Main Runner Function #########################\n\ndef run_grid_gen(pass_through_obj, input_file: str, output_folder_base: str, output_folder_name: str = None, do_overwrite: bool = False,\n               fast_skip: bool = False, generate_page: bool = True, publish_gen_metadata: bool = True, dry_run: bool = False, manual_pairs: list = None, allow_includes: bool = True, skip_invalid: bool = False):\n    grid = GridFileHelper()\n    grid.stylesheet = ''\n    grid.skip_invalid = skip_invalid\n    yaml_content = None\n    if manual_pairs is None:\n        full_input_path = ASSET_DIR + \"/\" + input_file\n        if not os.path.exists(full_input_path):\n            raise RuntimeError(f\"Non-existent file '{input_file}'\")\n        # Parse and verify\n        with open(full_input_path, 'r', encoding=\"utf-8\") as yaml_content_text:\n            try:\n                if allow_includes:\n                    yaml_content = yaml.load(yaml_content_text, Loader=GridYamlLoader)\n                else:\n                    yaml_content = yaml.safe_load(yaml_content_text)\n            except yaml.YAMLError as exc:\n                raise RuntimeError(f\"Invalid YAML in file '{input_file}': {exc}\")\n        grid.parse_yaml(yaml_content, input_file)\n    else:\n        grid.title = output_folder_name\n        grid.description = \"\"\n        grid.variables = dict()\n        grid.author = \"Unspecified\"\n        grid.format = \"png\"\n        grid.axes = list()\n        grid.params = None\n        grid.grid_obj = {}\n        yaml_content = {\n            'grid': {\n                'title': grid.title,\n                'description': grid.description,\n                'format': grid.format,\n                'author': grid.author\n            },\n            'axes': {}\n        }\n        for i in range(0, int(len(manual_pairs) / 2)):\n            key = manual_pairs[i * 2]\n            if isinstance(key, str) and key.strip() != \"\":\n                try:\n                    val = manual_pairs[i * 2 + 1]\n                    grid.axes.append(Axis(grid, key, val))\n                    yaml_key = key\n                    duplicates = 1\n                    while yaml_key in yaml_content['axes']:\n                        duplicates += 1\n                        yaml_key = f\"{key} {duplicates}\"\n                    yaml_content['axes'][yaml_key] = val\n                except Exception as e:\n                    raise RuntimeError(f\"Invalid axis {(i + 1)} '{key}': errored: {e}\")\n    # Now start using it\n    if output_folder_name.strip() == \"\":\n        if grid.out_path is None:\n            output_folder_name = input_file.replace(\".yml\", \"\")\n        else:\n            output_folder_name = grid.out_path.strip()\n    if os.path.isabs(output_folder_name):\n        folder = output_folder_name\n    else:\n        folder = output_folder_base + \"/\" + output_folder_name\n    runner = GridRunner(grid, do_overwrite, folder, pass_through_obj, fast_skip)\n    runner.preprocess()\n    if generate_page:\n        json = WebDataBuilder.emit_web_data(folder, grid, publish_gen_metadata, pass_through_obj, yaml_content, dry_run)\n    result = runner.run(dry_run)\n    if dry_run:\n        print(\"Infinite Grid dry run succeeded without error\")\n    else:\n        json = json.replace('\"will_run\": true, ', '')\n        with open(folder + \"/data.js\", 'w', encoding=\"utf-8\") as f:\n            f.write(\"rawData = \" + json)\n        os.remove(folder + \"/last.js\")\n    return result\n"
  },
  {
    "path": "install.py",
    "content": "import launch\n\nif not launch.is_installed(\"yaml\"):\n    launch.run_pip(\"install pyyaml\", \"pyyaml for Infinity Grid Script\")\nif not launch.is_installed(\"yamlinclude\"):\n    launch.run_pip(\"install pyyaml-include\", \"pyyaml-include for Infinity Grid Script\")\n"
  },
  {
    "path": "javascript/infinity_grid.js",
    "content": "/**\n * Stable Diffusion Infinity Grid Generator\n *\n * Author: Alex 'mcmonkey' Goodwin\n *\n * GitHub URL: https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script\n * Created: 2022/12/08\n * Last updated: 2023/02/19\n *\n * For usage help, view the README.md file in the extension root, or via the GitHub page.\n *\n */\n\n// Title injection code referenced from d8ahazard's Dreambooth extension\nex_titles = titles;\n\nnew_titles = {\n    \"Select grid definition file\": \"Select the grid definition yaml file, in your '(extension)/assets' folder. Refer to the README for info.\",\n    \"Overwrite existing images (for updating grids)\": \"If checked, any existing image files will be overwritten - this is useful if you want to redo the grid with completely different base settings. If unchecked, if an image already exists, it will be skipped - this is useful for adding new options to an existing grid.\",\n    \"Generate infinite-grid webviewer page\": \"If checked, generate the webviewer page. If unchecked, won't generate. You can uncheck this for dryruns that don't need it, or to avoid overwriting customized pages.\",\n    \"Do a dry run to validate your grid file\": \"If checked, no images will be rendered - it will just validate your YAML and all its content. Check the WebUI's console for any messages.\",\n    \"Publish full generation metadata for viewing on-page\": \"If checked, any/all image metadata will be stored in the webpage's files, and the internal values of each axis. This is useful for viewing, but if you're sharing a generation where some details are private (eg exact prompt text) you'll want to uncheck this. Note that this doesn't change whether metadata gets stored in images or not, edit your Settings tab to configure that.\",\n    \"Use more-performant skipping\": \"Only matters if you have 'skip: true' on any values - if checked, uses a method of skipping that improves performance but prevents validation of the skipped options.\",\n    \"Validate PromptReplace input\": \"If unchecked, will allow useless PromptReplace settings to be ignored. If checked, will error if the replace won't do anything.\"\n}\n\nfor (var i = 1; i <= 16; i++) {\n    new_titles[`Axis ${i} Mode`] = \"Select the desired mode / setting - ie what value it is that should be changing, for this axis. You have as many axes as you need, just select modes and more will be added as you go.\";\n    new_titles[`Axis ${i} Value`] = \"Fill in values applicable to the mode, separated by commas. If it's a numeric mode, you can do for example '1, 2, 3'.\";\n}\n\nex_titles = Object.assign({}, ex_titles, new_titles);\ntitles = ex_titles;\n"
  },
  {
    "path": "scripts/infinity_grid.py",
    "content": "##################\n# Stable Diffusion Infinity Grid Generator\n#\n# Author: Alex 'mcmonkey' Goodwin\n# GitHub URL: https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script\n# Created: 2022/12/08\n# Last updated: 2023/02/19\n# License: MIT\n#\n# For usage help, view the README.md file in the extension root, or via the GitHub page.\n#\n##################\n\nimport gradio as gr\nimport os, numpy, threading\nfrom copy import copy\nfrom datetime import datetime\nfrom modules import images, shared, sd_models, sd_vae, sd_samplers, scripts, processing, ui_components\nfrom modules.processing import process_images, Processed\nfrom modules.shared import opts, state\nfrom PIL import Image\nimport gridgencore as core\nfrom gridgencore import clean_name, clean_mode, get_best_in_list, choose_better_file_name, GridSettingMode, fix_num, apply_field, registerMode\n\n######################### Constants #########################\nrefresh_symbol = '\\U0001f504'  # 🔄\nfill_values_symbol = \"\\U0001f4d2\"  # 📒\nINF_GRID_README = \"https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script\"\ncore.EXTRA_FOOTER = 'Images area auto-generated by an AI (Stable Diffusion) and so may not have been reviewed by the page author before publishing.\\n<script src=\"a1111webui.js?vary=9\"></script>'\ncore.EXTRA_ASSETS = [\"a1111webui.js\"]\n\n######################### Value Mode Helpers #########################\n\ndef get_model_for(name):\n    return get_best_in_list(name, map(lambda m: m.title, sd_models.checkpoints_list.values()))\n\ndef apply_model(p, v):\n    opts.sd_model_checkpoint = get_model_for(v)\n    sd_models.reload_model_weights()\n\ndef clean_model(p, v):\n    actual_model = get_model_for(v)\n    if actual_model is None:\n        raise RuntimeError(f\"Invalid parameter '{p}' as '{v}': model name unrecognized - valid {list(map(lambda m: m.title, sd_models.checkpoints_list.values()))}\")\n    return choose_better_file_name(v, actual_model)\n\ndef get_vae_for(name):\n    return get_best_in_list(name, sd_vae.vae_dict.keys())\n\ndef apply_vae(p, v):\n    vae_name = clean_name(v)\n    if vae_name == \"none\":\n        vae_name = \"None\"\n    elif vae_name in [\"auto\", \"automatic\"]:\n        vae_name = \"Automatic\"\n    else:\n        vae_name = get_vae_for(vae_name)\n    opts.sd_vae = vae_name\n    sd_vae.reload_vae_weights(None)\n\ndef clean_vae(p, v):\n    vae_name = clean_name(v)\n    if vae_name in [\"none\", \"auto\", \"automatic\"]:\n        return vae_name\n    actual_vae = get_vae_for(vae_name)\n    if actual_vae is None:\n        raise RuntimeError(f\"Invalid parameter '{p}' as '{v}': VAE name unrecognized - valid: {list(sd_vae.vae_dict.keys())}\")\n    return choose_better_file_name(v, actual_vae)\n\ndef apply_codeformer_weight(p, v):\n    opts.code_former_weight = float(v)\n\ndef apply_restore_faces(p, v):\n    input = str(v).lower().strip()\n    if input == \"false\":\n        p.restore_faces = False\n        return\n    p.restore_faces = True\n    restorer = get_best_in_list(input, map(lambda m: m.name(), shared.face_restorers))\n    if restorer is not None:\n        opts.face_restoration_model = restorer\n\ndef prompt_replace_parse_list(in_list):\n    if not any(('=' in x) for x in in_list):\n        first_val = in_list[0]\n        for x in range(0, len(in_list)):\n            in_list[x] = {\n                \"title\": in_list[x],\n                \"params\": {\n                    \"promptreplace\": f\"{first_val}={in_list[x]}\"\n                }\n            }\n    return in_list\n\ndef apply_prompt_replace(p, v):\n    val = v.split('=', maxsplit=1)\n    if len(val) != 2:\n        raise RuntimeError(f\"Invalid prompt replace, missing '=' symbol, for '{v}'\")\n    match = val[0].strip()\n    replace = val[1].strip()\n    if Script.VALIDATE_REPLACE and match not in p.prompt and match not in p.negative_prompt:\n        raise RuntimeError(f\"Invalid prompt replace, '{match}' is not in prompt '{p.prompt}' nor negative prompt '{p.negative_prompt}'\")\n    p.prompt = p.prompt.replace(match, replace)\n    p.negative_prompt = p.negative_prompt.replace(match, replace)\n\ndef apply_enable_hr(p, v):\n    p.enable_hr = v\n    if v:\n        if p.denoising_strength is None:\n            p.denoising_strength = 0.75\n\ndef apply_styles(p, v: str):\n    p.styles = list(v.split(','))\n\ndef apply_setting_override(name: str):\n    def applier(p, v):\n        p.override_settings[name] = v\n    return applier\n\n######################### Value Modes #########################\nhas_inited = False\n\ndef try_init():\n    global has_inited\n    if has_inited:\n        return\n    has_inited = True\n    core.grid_call_init_hook = a1111_grid_call_init_hook\n    core.grid_call_param_add_hook = a1111_grid_call_param_add_hook\n    core.grid_call_apply_hook = a1111_grid_call_apply_hook\n    core.grid_runner_pre_run_hook = a1111_grid_runner_pre_run_hook\n    core.grid_runner_pre_dry_hook = a1111_grid_runner_pre_dry_hook\n    core.grid_runner_post_dry_hook = a1111_grid_runner_post_dry_hook\n    core.grid_runner_count_steps = a1111_grid_runner_count_steps\n    core.webdata_get_base_param_data = a1111_webdata_get_base_param_data\n    registerMode(\"Model\", GridSettingMode(dry=False, type=\"text\", apply=apply_model, clean=clean_model, valid_list=lambda: list(map(lambda m: m.title, sd_models.checkpoints_list.values()))))\n    registerMode(\"VAE\", GridSettingMode(dry=False, type=\"text\", apply=apply_vae, clean=clean_vae, valid_list=lambda: list(sd_vae.vae_dict.keys()) + ['none', 'auto', 'automatic']))\n    registerMode(\"Sampler\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"sampler_name\"), valid_list=lambda: list(sd_samplers.all_samplers_map.keys())))\n    registerMode(\"Seed\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"seed\")))\n    registerMode(\"Steps\", GridSettingMode(dry=True, type=\"integer\", min=0, max=200, apply=apply_field(\"steps\")))\n    registerMode(\"CFG Scale\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=500, apply=apply_field(\"cfg_scale\")))\n    registerMode(\"Width\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"width\")))\n    registerMode(\"Height\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"height\")))\n    registerMode(\"Prompt\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"prompt\")))\n    registerMode(\"Negative Prompt\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"negative_prompt\")))\n    registerMode(\"Prompt Replace\", GridSettingMode(dry=True, type=\"text\", apply=apply_prompt_replace, parse_list=prompt_replace_parse_list))\n    registerMode(\"Styles\", GridSettingMode(dry=True, type=\"text\", apply=apply_styles, valid_list=lambda: list(shared.prompt_styles.styles)))\n    registerMode(\"Var Seed\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"subseed\")))\n    registerMode(\"Var Strength\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"subseed_strength\")))\n    registerMode(\"ClipSkip\", GridSettingMode(dry=False, type=\"integer\", min=1, max=12, apply=apply_setting_override(\"CLIP_stop_at_last_layers\")))\n    registerMode(\"Denoising\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"denoising_strength\")))\n    registerMode(\"ETA\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"eta\")))\n    registerMode(\"Sigma Churn\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"s_churn\")))\n    registerMode(\"Sigma TMin\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"s_tmin\")))\n    registerMode(\"Sigma TMax\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"s_tmax\")))\n    registerMode(\"Sigma Noise\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"s_noise\")))\n    registerMode(\"Out Width\", GridSettingMode(dry=True, type=\"integer\", min=0, apply=apply_field(\"inf_grid_out_width\")))\n    registerMode(\"Out Height\", GridSettingMode(dry=True, type=\"integer\", min=0, apply=apply_field(\"inf_grid_out_height\")))\n    registerMode(\"Restore Faces\", GridSettingMode(dry=True, type=\"text\", apply=apply_restore_faces, valid_list=lambda: list(map(lambda m: m.name(), shared.face_restorers)) + [\"true\", \"false\"]))\n    registerMode(\"CodeFormer Weight\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_codeformer_weight))\n    registerMode(\"Tiling\", GridSettingMode(dry=True, type=\"boolean\", apply=apply_field(\"tiling\")))\n    registerMode(\"Image Mask Weight\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"inpainting_mask_weight\")))\n    registerMode(\"ETA Noise Seed Delta\", GridSettingMode(dry=True, type=\"integer\", apply=apply_setting_override(\"eta_noise_seed_delta\")))\n    registerMode(\"Enable HighRes Fix\", GridSettingMode(dry=True, type=\"boolean\", apply=apply_enable_hr))\n    registerMode(\"HighRes Scale\", GridSettingMode(dry=True, type=\"decimal\", min=1, max=16, apply=apply_field(\"hr_scale\")))\n    registerMode(\"HighRes Steps\", GridSettingMode(dry=True, type=\"integer\", min=0, max=200, apply=apply_field(\"hr_second_pass_steps\")))\n    registerMode(\"HighRes Resize Width\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"hr_resize_x\")))\n    registerMode(\"HighRes Resize Height\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"hr_resize_y\")))\n    registerMode(\"HighRes Upscale to Width\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"hr_upscale_to_x\")))\n    registerMode(\"HighRes Upscale to Height\", GridSettingMode(dry=True, type=\"integer\", apply=apply_field(\"hr_upscale_to_y\")))\n    registerMode(\"HighRes Upscaler\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"hr_upscaler\"), valid_list=lambda: list(map(lambda u: u.name, shared.sd_upscalers)) + list(shared.latent_upscale_modes.keys())))\n    registerMode(\"HighRes Sampler\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"hr_sampler_name\"), valid_list=lambda: list(sd_samplers.all_samplers_map.keys())))\n    registerMode(\"HighRes Checkpoint\", GridSettingMode(dry=False, type=\"text\", apply=apply_field(\"hr_checkpoint_name\"), clean=clean_model, valid_list=lambda: list(map(lambda m: m.title, sd_models.checkpoints_list.values()))))\n    registerMode(\"Image CFG Scale\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=500, apply=apply_field(\"image_cfg_scale\")))\n    registerMode(\"Use Result Index\", GridSettingMode(dry=True, type=\"integer\", min=0, max=500, apply=apply_field(\"inf_grid_use_result_index\")))\n    try:\n        script_list = [x for x in scripts.scripts_data if x.script_class.__module__ == \"dynamic_thresholding.py\"][:1]\n        if len(script_list) == 1:\n            dynamic_thresholding = script_list[0].module\n            registerMode(\"[DynamicThreshold] Enable\", GridSettingMode(dry=True, type=\"boolean\", apply=apply_field(\"dynthres_enabled\")))\n            registerMode(\"[DynamicThreshold] Mimic Scale\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=500, apply=apply_field(\"dynthres_mimic_scale\")))\n            registerMode(\"[DynamicThreshold] Threshold Percentile\", GridSettingMode(dry=True, type=\"decimal\", min=0.0, max=100.0, apply=apply_field(\"dynthres_threshold_percentile\")))\n            registerMode(\"[DynamicThreshold] Mimic Mode\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"dynthres_mimic_mode\"), valid_list=lambda: list(dynamic_thresholding.VALID_MODES)))\n            registerMode(\"[DynamicThreshold] CFG Mode\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"dynthres_cfg_mode\"), valid_list=lambda: list(dynamic_thresholding.VALID_MODES)))\n            registerMode(\"[DynamicThreshold] Mimic Scale Minimum\", GridSettingMode(dry=True, type=\"decimal\", min=0.0, max=100.0, apply=apply_field(\"dynthres_mimic_scale_min\")))\n            registerMode(\"[DynamicThreshold] CFG Scale Minimum\", GridSettingMode(dry=True, type=\"decimal\", min=0.0, max=100.0, apply=apply_field(\"dynthres_cfg_scale_min\")))\n            registerMode(\"[DynamicThreshold] Experiment Mode\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=100000, apply=apply_field(\"dynthres_experiment_mode\")))\n            registerMode(\"[DynamicThreshold] Scheduler Value\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=100, apply=apply_field(\"dynthres_scheduler_val\")))\n            registerMode(\"[DynamicThreshold] Scaling Startpoint\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"dynthres_scaling_startpoint\"), valid_list=lambda: list(['ZERO', 'MEAN'])))\n            registerMode(\"[DynamicThreshold] Variability Measure\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"dynthres_variability_measure\"), valid_list=lambda: list(['STD', 'AD'])))\n            registerMode(\"[DynamicThreshold] Interpolate Phi\", GridSettingMode(dry=True, type=\"decimal\", min=0, max=1, apply=apply_field(\"dynthres_interpolate_phi\")))\n            registerMode(\"[DynamicThreshold] Separate Feature Channels\", GridSettingMode(dry=True, type=\"boolean\", apply=apply_field(\"dynthres_separate_feature_channels\")))\n        script_list = [x for x in scripts.scripts_data if x.script_class.__module__ == \"controlnet.py\"][:1]\n        if len(script_list) == 1:\n            # Hacky but works\n            module = script_list[0].module\n            preprocessors_list = list(p.name for p in module.Preprocessor.get_sorted_preprocessors())\n            def validate_param(p, v):\n                if not shared.opts.data.get(\"control_net_allow_script_control\", False):\n                    raise RuntimeError(\"ControlNet options cannot currently work, you must enable 'Allow other script to control this extension' in Settings -> ControlNet first\")\n                return v\n            registerMode(\"[ControlNet] Enable\", GridSettingMode(dry=True, type=\"boolean\", apply=apply_field(\"control_net_enabled\"), clean=validate_param))\n            registerMode(\"[ControlNet] Preprocessor\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"control_net_module\"), clean=validate_param, valid_list=lambda: list(preprocessors_list)))\n            registerMode(\"[ControlNet] Model\", GridSettingMode(dry=True, type=\"text\", apply=apply_field(\"control_net_model\"), clean=validate_param, valid_list=lambda: list(list(module.global_state.cn_models.keys()))))\n            registerMode(\"[ControlNet] Weight\", GridSettingMode(dry=True, type=\"decimal\", min=0.0, max=2.0, apply=apply_field(\"control_net_weight\"), clean=validate_param))\n            registerMode(\"[ControlNet] Guidance Strength\", GridSettingMode(dry=True, type=\"decimal\", min=0.0, max=1.0, apply=apply_field(\"control_net_guidance_strength\"), clean=validate_param))\n            registerMode(\"[ControlNet] Annotator Resolution\", GridSettingMode(dry=True, type=\"integer\", min=0, max=2048, apply=apply_field(\"control_net_pres\"), clean=validate_param))\n            registerMode(\"[ControlNet] Threshold A\", GridSettingMode(dry=True, type=\"integer\", min=0, max=256, apply=apply_field(\"control_net_pthr_a\"), clean=validate_param))\n            registerMode(\"[ControlNet] Threshold B\", GridSettingMode(dry=True, type=\"integer\", min=0, max=256, apply=apply_field(\"control_net_pthr_b\"), clean=validate_param))\n            registerMode(\"[ControlNet] Image\", GridSettingMode(dry=True, type=\"text\", apply=core.apply_field_as_image_data(\"control_net_input_image\"), clean=validate_param, valid_list=lambda: core.list_image_files()))\n    except Exception as e:\n        print(f\"Infinity Grid Generator failed to import a dependency module: {e}\")\n        pass\n\n######################### Actual Execution Logic #########################\n\ndef a1111_grid_call_init_hook(grid_call: core.SingleGridCall):\n    grid_call.replacements = list()\n\ndef a1111_grid_call_param_add_hook(grid_call: core.SingleGridCall, param: str, value):\n    if grid_call.grid.min_width is None:\n        grid_call.grid.min_width = grid_call.grid.initial_p.width\n    if grid_call.grid.min_height is None:\n        grid_call.grid.min_height = grid_call.grid.initial_p.height\n    cleaned = clean_mode(param)\n    if cleaned == \"promptreplace\":\n        grid_call.replacements.append(value)\n        return True\n    elif cleaned in [\"width\", \"outwidth\"]:\n        grid_call.grid.min_width = min(grid_call.grid.min_width or 99999, int(value))\n    elif cleaned in [\"height\", \"outheight\"]:\n        grid_call.grid.min_height = min(grid_call.grid.min_height or 99999, int(value))\n    return False\n\ndef a1111_grid_call_apply_hook(grid_call: core.SingleGridCall, param: str, dry: bool):\n    for replace in grid_call.replacements:\n        apply_prompt_replace(param, replace)\n    \ndef a1111_grid_runner_pre_run_hook(grid_runner: core.GridRunner):\n    state.job_count = grid_runner.total_run\n    shared.total_tqdm.updateTotal(grid_runner.total_steps)\n    # prevents the steps from from being recalculated by Auto1 using the current value of hires steps\n    state.processing_has_refined_job_count = True\n\nclass TempHolder: pass\n\ndef a1111_grid_runner_pre_dry_hook(grid_runner: core.GridRunner):\n    grid_runner.temp = TempHolder()\n    grid_runner.temp.old_codeformer_weight = opts.code_former_weight\n    grid_runner.temp.old_face_restorer = opts.face_restoration_model\n    grid_runner.temp.old_vae = opts.sd_vae\n    grid_runner.temp.old_model = opts.sd_model_checkpoint\n\ndef a1111_grid_runner_post_dry_hook(grid_runner: core.GridRunner, p, set):\n    p.seed = processing.get_fixed_seed(p.seed)\n    p.subseed = processing.get_fixed_seed(p.subseed)\n    processed = process_images(p)\n    if len(processed.images) < 1:\n        raise RuntimeError(f\"Something went wrong! Image gen '{set.data}' produced {len(processed.images)} images, which is wrong\")\n    os.makedirs(os.path.dirname(set.filepath), exist_ok=True)\n    result_index = getattr(p, 'inf_grid_use_result_index', 0)\n    if result_index >= len(processed.images):\n        result_index = len(processed.images) - 1\n    img = processed.images[result_index]\n    if type(img) == numpy.ndarray:\n        img = Image.fromarray(img)\n    if hasattr(p, 'inf_grid_out_width') and hasattr(p, 'inf_grid_out_height'):\n        img = img.resize((p.inf_grid_out_width, p.inf_grid_out_height), resample=images.LANCZOS)\n    processed.images[result_index] = img\n    info = processing.create_infotext(p, [p.prompt], [p.seed], [p.subseed], [])\n    ext = grid_runner.grid.format\n    prompt = p.prompt\n    seed = processed.seed\n    def save_offthread():\n        images.save_image(img, path=os.path.dirname(set.filepath), basename=\"\", forced_filename=os.path.basename(set.filepath), save_to_dirs=False, info=info, extension=ext, p=p, prompt=prompt, seed=seed)\n    threading.Thread(target=save_offthread).start()\n    opts.code_former_weight = grid_runner.temp.old_codeformer_weight\n    opts.face_restoration_model = grid_runner.temp.old_face_restorer\n    opts.sd_vae = grid_runner.temp.old_vae\n    opts.sd_model_checkpoint = grid_runner.temp.old_model\n    grid_runner.temp = None\n    return processed\n\ndef a1111_grid_runner_count_steps(grid_runner: core.GridRunner, set):\n    step_count = set.params.get(\"steps\")\n    step_count = int(step_count) if step_count is not None else grid_runner.p.steps\n    total_steps = step_count\n    enable_hr = set.params.get(\"enable highres fix\")\n    if enable_hr is None:\n        enable_hr = grid_runner.p.enable_hr if hasattr(grid_runner.p, 'enable_hr') else False\n    if enable_hr:\n        highres_steps = set.params.get(\"highres steps\")\n        highres_steps = int(highres_steps) if highres_steps is not None else (grid_runner.p.hr_second_pass_steps or step_count)\n        total_steps += highres_steps\n    return total_steps\n\ndef a1111_webdata_get_base_param_data(p):\n    return {\n        \"sampler\": p.sampler_name,\n        \"seed\": p.seed,\n        \"restorefaces\": (opts.face_restoration_model if p.restore_faces else None),\n        \"steps\": p.steps,\n        \"cfgscale\": p.cfg_scale,\n        \"model\": choose_better_file_name('', shared.sd_model.sd_checkpoint_info.model_name).replace(',', '').replace(':', ''),\n        \"vae\": (None if sd_vae.loaded_vae_file is None else (choose_better_file_name('', sd_vae.loaded_vae_file).replace(',', '').replace(':', ''))),\n        \"width\": p.width,\n        \"height\": p.height,\n        \"prompt\": p.prompt,\n        \"negativeprompt\": p.negative_prompt,\n        \"varseed\": (None if p.subseed_strength == 0 else p.subseed),\n        \"varstrength\": (None if p.subseed_strength == 0 else p.subseed_strength),\n        \"clipskip\": opts.CLIP_stop_at_last_layers,\n        \"codeformerweight\": opts.code_former_weight,\n        \"denoising\": getattr(p, 'denoising_strength', None),\n        \"eta\": fix_num(p.eta),\n        \"sigmachurn\": fix_num(p.s_churn),\n        \"sigmatmin\": fix_num(p.s_tmin),\n        \"sigmatmax\": fix_num(p.s_tmax),\n        \"sigmanoise\": fix_num(p.s_noise),\n        \"ENSD\": None if opts.eta_noise_seed_delta == 0 else opts.eta_noise_seed_delta\n    }\n\nclass SettingsFixer():\n    def __enter__(self):\n        self.model = opts.sd_model_checkpoint\n        self.code_former_weight = opts.code_former_weight\n        self.face_restoration_model = opts.face_restoration_model\n        self.vae = opts.sd_vae\n\n    def __exit__(self, exc_type, exc_value, tb):\n        opts.code_former_weight = self.code_former_weight\n        opts.face_restoration_model = self.face_restoration_model\n        opts.sd_vae = self.vae\n        opts.sd_model_checkpoint = self.model\n        sd_models.reload_model_weights()\n        sd_vae.reload_vae_weights()\n\n######################### Script class entrypoint #########################\nclass Script(scripts.Script):\n    BASEDIR = scripts.basedir()\n    VALIDATE_REPLACE = True\n\n    def title(self):\n        return \"Generate Infinite-Axis Grid\"\n\n    def show(self, is_img2img):\n        return True\n\n    def ui(self, is_img2img):\n        core.list_image_files()\n        try_init()\n        gr.HTML(value=f\"<br>Confused/new? View <a style=\\\"border-bottom: 1px #00ffff dotted;\\\" href=\\\"{INF_GRID_README}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">the README</a> for usage instructions.<br><br>\")\n        with gr.Row():\n            grid_file = gr.Dropdown(value=\"Create in UI\",label=\"Select grid definition file\", choices=[\"Create in UI\"] + core.get_name_list())\n            def refresh():\n                new_choices = [\"Create in UI\"] + core.get_name_list()\n                grid_file.choices = new_choices\n                return gr.update(choices=new_choices)\n            refresh_button = ui_components.ToolButton(value=refresh_symbol, elem_id=\"infinity_grid_refresh_button\")\n            refresh_button.click(fn=refresh, inputs=[], outputs=[grid_file])\n        output_file_path = gr.Textbox(value=\"\", label=\"Output folder name (if blank uses yaml's 'outpath' parameter, filename, or current date)\")\n        page_will_be = gr.HTML(value=\"(...)<br><br>\")\n        manual_group = gr.Group(visible=True)\n        manual_axes = list()\n        sets = list()\n        def get_page_url_text(file):\n            if file is None:\n                return \"(...)\"\n            notice = \"\"\n            if not os.path.isabs(file):\n                out_path = opts.outdir_grids or (opts.outdir_img2img_grids if is_img2img else opts.outdir_txt2img_grids)\n                full_out_path = out_path + \"/\" + file\n                url = \"/file=\" + full_out_path\n            else:\n                full_out_path = file\n                url = \"file://\" + (\"\" if file.startswith(\"/\") else \"/\") + file\n                notice = \"<br><span style=\\\"color: red;\\\">This is a raw file path, not within the WebUI output directory. You may need to open the output file manually.</span>\"\n            if os.path.exists(full_out_path):\n                notice += \"<br><span style=\\\"color: red;\\\">NOTICE: There is already something saved there! This will overwrite prior data.</span>\"\n            return f\"Page will be at <a style=\\\"border-bottom: 1px #00ffff dotted;\\\" href=\\\"{url}/index.html\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">(Click me) <code>{full_out_path}</code></a>{notice}<br><br>\"\n        def update_page_url(file_path, selected_file):\n            out_file_update = gr.Textbox.update()\n            if file_path == \"\" and selected_file == \"Create in UI\":\n                file_path = f\"autonamed_inf_grid_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}\"\n                out_file_update = gr.Textbox.update(value=file_path)\n            info_update = gr.update(value=get_page_url_text(file_path or (selected_file.replace(\".yml\", \"\") if selected_file is not None else None)))\n            return [out_file_update, info_update]\n        def update_page_url_single(file_path, selected_file):\n            (_, info_update) = update_page_url(file_path, selected_file)\n            return info_update\n        with manual_group:\n            with gr.Row():\n                with gr.Column():\n                    axis_count = 0\n                    for group in range(0, 4):\n                        group_obj = gr.Group(visible=group == 0)\n                        with group_obj:\n                            rows = list()\n                            for i in range(0, 4):\n                                with gr.Row():\n                                    axis_count += 1\n                                    row_mode = gr.Dropdown(value=\"\", label=f\"Axis {axis_count} Mode\", choices=[\" \"] + [x.name for x in core.valid_modes.values()])\n                                    row_value = gr.Textbox(label=f\"Axis {axis_count} Value\", lines=1)\n                                    fill_row_button = ui_components.ToolButton(value=fill_values_symbol, visible=False)\n                                    def fill_axis(mode_name):\n                                        core.clear_caches()\n                                        mode = core.valid_modes.get(clean_mode(mode_name))\n                                        if mode is None:\n                                            return gr.update()\n                                        elif mode.type == \"boolean\":\n                                            return \"true, false\"\n                                        elif mode.valid_list is not None:\n                                            return \", \".join(list(mode.valid_list()))\n                                        raise RuntimeError(f\"Can't fill axis for {mode_name}\")\n                                    fill_row_button.click(fn=fill_axis, inputs=[row_mode], outputs=[row_value])\n                                    def on_axis_change(mode_name, out_file):\n                                        mode = core.valid_modes.get(clean_mode(mode_name))\n                                        button_update = gr.Button.update(visible=mode is not None and (mode.valid_list is not None or mode.type == \"boolean\"))\n                                        (out_file_update, info_update) = update_page_url(out_file, \"Create in UI\")\n                                        return [button_update, out_file_update, info_update]\n                                    row_mode.change(fn=on_axis_change, inputs=[row_mode, output_file_path], outputs=[fill_row_button, output_file_path, page_will_be])\n                                    manual_axes += list([row_mode, row_value])\n                                    rows.append(row_mode)\n                            sets.append([group_obj, rows])\n        for group in range(0, 3):\n            row_mode = sets[group][1][3]\n            group_obj = sets[group + 1][0]\n            next_rows = sets[group + 1][1]\n            def make_vis(prior, r1, r2, r3, r4):\n                return gr.Group.update(visible=(prior+r1+r2+r3+r4).strip() != \"\")\n            row_mode.change(fn=make_vis, inputs=[row_mode] + next_rows, outputs=[group_obj])\n        gr.HTML('<span style=\"opacity:0.5;\">(More input rows will be automatically added after you select modes above.)</span>')\n        grid_file.change(\n            fn=lambda x: {\"visible\": x == \"Create in UI\", \"__type__\": \"update\"},\n            inputs=[grid_file],\n            outputs=[manual_group],\n            show_progress = False)\n        output_file_path.change(fn=update_page_url_single, inputs=[output_file_path, grid_file], outputs=[page_will_be])\n        grid_file.change(fn=update_page_url, inputs=[output_file_path, grid_file], outputs=[output_file_path, page_will_be])\n        with gr.Row():\n            do_overwrite = gr.Checkbox(value=False, label=\"Overwrite existing images (for updating grids)\")\n            dry_run = gr.Checkbox(value=False, label=\"Do a dry run to validate your grid file\")\n            fast_skip = gr.Checkbox(value=False, label=\"Use more-performant skipping\")\n            skip_invalid = gr.Checkbox(value=False, label=\"Skip invalid entries\")\n        with gr.Row():\n            generate_page = gr.Checkbox(value=True, label=\"Generate infinite-grid webviewer page\")\n            validate_replace = gr.Checkbox(value=True, label=\"Validate PromptReplace input\")\n            publish_gen_metadata = gr.Checkbox(value=True, label=\"Publish full generation metadata for viewing on-page\")\n        return [do_overwrite, generate_page, dry_run, validate_replace, publish_gen_metadata, grid_file, fast_skip, output_file_path, skip_invalid] + manual_axes\n\n    def run(self, p, do_overwrite, generate_page, dry_run, validate_replace, publish_gen_metadata, grid_file, fast_skip, output_file_path, skip_invalid, *manual_axes):\n        core.clear_caches()\n        try_init()\n        # Clean up default params\n        p = copy(p)\n        p.n_iter = 1\n        p.batch_size = 1\n        p.do_not_save_samples = True\n        p.do_not_save_grid = True\n        p.seed = processing.get_fixed_seed(p.seed)\n        # Store extra variable\n        Script.VALIDATE_REPLACE = validate_replace\n        # Validate to avoid abuse\n        if '..' in grid_file or grid_file == \"\":\n            raise RuntimeError(f\"Unacceptable filename '{grid_file}'\")\n        if '..' in output_file_path:\n            raise RuntimeError(f\"Unacceptable alt file path '{output_file_path}'\")\n        if grid_file == \"Create in UI\":\n            if output_file_path is None or output_file_path == \"\":\n                raise RuntimeError(f\"Must specify the output file path\")\n            manual_axes = list(manual_axes)\n        else:\n            manual_axes = None\n        with SettingsFixer():\n            result = core.run_grid_gen(p, grid_file, p.outpath_grids, output_file_path, do_overwrite, fast_skip, generate_page, publish_gen_metadata, dry_run, manual_axes, skip_invalid=skip_invalid)\n        if result is None:\n            return Processed(p, list())\n        return result\n"
  },
  {
    "path": "style.css",
    "content": "/**\n * This file is part of Stable Diffusion Infinity Grid Generator, view the README.md for more information.\n */\n\n#infinity_grid_refresh_button {\n    max-width: 2.5em;\n    min-width: 2.5em;\n    height: 2.4em;\n}\n"
  }
]