Upload 69 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- config.jsonAdded+14
- extensions/a.txtAdded+1
- extensions/sd-webui-detail-daemon/.gitattributesAdded+2
- extensions/sd-webui-detail-daemon/.gitignoreAdded+1
- extensions/sd-webui-detail-daemon/LICENSEAdded+21
- extensions/sd-webui-detail-daemon/README.mdAdded+82
- extensions/sd-webui-detail-daemon/a.txtAdded+1
- extensions/sd-webui-detail-daemon/scripts/__pycache__/a.txtAdded+1
- extensions/sd-webui-detail-daemon/scripts/__pycache__/detail_daemon.cpython-310.pycAdded
- extensions/sd-webui-detail-daemon/scripts/a.txtAdded+1
- extensions/sd-webui-detail-daemon/scripts/detail_daemon.pyAdded+313
- extensions/sd-webui-detail-daemon/style.cssAdded+20
- extensions/sd-webui-vectorscope-cc/.github/FUNDING.ymlAdded+1
- extensions/sd-webui-vectorscope-cc/.github/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/.gitignoreAdded+2
- extensions/sd-webui-vectorscope-cc/CHANGELOG.mdAdded+145
- extensions/sd-webui-vectorscope-cc/LICENSEAdded+21
- extensions/sd-webui-vectorscope-cc/README.mdAdded+375
- extensions/sd-webui-vectorscope-cc/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/javascript/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/javascript/vec_cc.jsAdded+128
- extensions/sd-webui-vectorscope-cc/lib_cc/__init__.pyAdded+4
- extensions/sd-webui-vectorscope-cc/lib_cc/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/lib_cc/callback.pyAdded+180
- extensions/sd-webui-vectorscope-cc/lib_cc/colorpicker.pyAdded+27
- extensions/sd-webui-vectorscope-cc/lib_cc/const.pyAdded+49
- extensions/sd-webui-vectorscope-cc/lib_cc/scaling.pyAdded+32
- extensions/sd-webui-vectorscope-cc/lib_cc/settings.pyAdded+79
- extensions/sd-webui-vectorscope-cc/lib_cc/style.pyAdded+108
- extensions/sd-webui-vectorscope-cc/lib_cc/xyz.pyAdded+70
- extensions/sd-webui-vectorscope-cc/samples/00.jpgAdded
- extensions/sd-webui-vectorscope-cc/samples/01.jpgAdded
- extensions/sd-webui-vectorscope-cc/samples/02.jpgAdded
- extensions/sd-webui-vectorscope-cc/samples/03.jpgAdded
- extensions/sd-webui-vectorscope-cc/samples/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/samples/api_example.jsonAdded+31
- extensions/sd-webui-vectorscope-cc/samples/method.jpgAdded
- extensions/sd-webui-vectorscope-cc/samples/scaling.jpgAdded
- extensions/sd-webui-vectorscope-cc/scripts/a.txtAdded+1
- extensions/sd-webui-vectorscope-cc/scripts/cc.pyAdded+430
- extensions/sd-webui-vectorscope-cc/scripts/cc_hdr.pyAdded+142
- extensions/sd-webui-vectorscope-cc/scripts/dot.pngAdded
- extensions/sd-webui-vectorscope-cc/scripts/vectorscope.pngAdded
- extensions/sd-webui-vectorscope-cc/style.cssAdded+39
- models/Codeformer/a.txtAdded+1
- models/ControlNet/a.txtAdded+1
- models/ControlNetPreprocessor/a.txtAdded+1
- models/ControlNetPreprocessor/clip_vision/a.txtAdded+1
- models/GFPGAN/a.txtAdded+1
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textextensions/sd-webui-vectorscope-cc/samples/scaling.jpg filter=lfs diff=lfs merge=lfs -text
1234567891011121314{
"sd_checkpoint_hash": "c87b5758c5319c1d30190b576a43f248fea100eb07553c1f79cedc4da94d1e52",
"sd_model_checkpoint": "ntrMIXIllustriousXL_v21.safetensors [c87b5758c5]",
"CLIP_stop_at_last_layers": 2,
"samples_format": "webp",
"grid_format": "webp",
"sd_vae": "sdxl_vae.safetensors",
"quicksettings_list": [
"sd_model_checkpoint",
"skip_early_cond"
],
"randn_source": "NV",
"emphasis": "No norm"
}1112# Auto detect text files and perform LF normalization
* text=auto1__pycache__/123456789101112131415161718192021MIT License
Copyright (c) 2024 Sahand Ahmadian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Detail Daemon
This is an extension for [Stable Diffusion Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui), which allows users to adjust the amount of detail/smoothness in an image, during the sampling steps.
It uses no LORAs, ControlNets, etc., and as a result its performance is not biased towards any certain style and it introduces no new stylistic or semantic features of its own into the generation. This also means that it can work with any model and on any type of image.
<sub>*Model: SSD-1B*<br></sub>

*Left: Less detail, Middle: Original, Right: More detail*<br>
<sub>*Model: SD 1.5 (finetuned)*<br></sub>

*Left: Less detail, Middle: Original, Right: More detail*<br>
## How It Works
Detail Daemon works by manipulating the original noise levels at every sampling step, according to a customizable schedule.
### In Theory
The noise levels (sigmas, i.e. the standard deviation of the noise) tell the model how much noise it should expect, and try to remove, at each denoising step. A higher sigma value at a certain denoising step tells the model to denoise more aggressively at that step and vice versa.
With a common sigmas schedule, the sigmas start at very high values at the beginning of the denoising process, then quickly fall to low values in the middle, and to very low values towards the end of the process. This curve (along with the timesteps schedule, but that's a story for another day) is what makes it so that larger features (low frequencies) of the image are defined at the earlier steps, and towards the end of the process you can only see minor changes in the smaller features (high frequencies). We'll get back to this later.
Now, if we pass the model a sigmas schedule with values lower than the original, at each step the model will denoise less, resulting a noisier output latent at that step. But then in the steps after that, the model does its best to make sense of this extra noise and turn it into image features. So in theory, *when done in modesty*, this would result in a more detailed image. If you push it too hard, the model won't be able to handle the extra noise added at each step and the end result will devolve into pure noise. So modesty is key.
### But in Practice
Modesty only gets you so far! Also, wtf are those? As the examples below show, you can't really add that much detail to the image before it either breaks down, and/or becomes a totally different thing.
<sub>*SD 1.5*<br></sub>

Original sigmas (left) multiplied by .9, .85, .8<br>
<sub>*SDXL*<br></sub>

Original sigmas (left) multiplied by .95, .9, .85, .875, .8<br>
That's because:
1. We're constantly adding noise and not giving the model enough time to deal with it
2. We are manipulating the early steps where the low frequency features of the image (color, composition, etc.) are defined
### Enter the Schedule
What we usually mean by "detail" falls within the mid to high frequency range, which correspond to the middle to late steps in the sampling process. So if we skip the early steps to leave the main features of the image intact, and the late steps to give the model some time to turn the extra noise into useful detail, we'll have something like this:

Then we could make our schedule a bit fancier and have it target specific steps corresponding to different sized details:

Which steps correspond to which exact frequency range depends on the model you're using, the sampler, your prompt (specially if you're using Prompt Editing and stuff), and probably a bunch of other things. There are also fancier things you can (and should) do with the schedule, like pushing the sigmas too low for some heavy extra noise and then too high to clean up the excess and leave some nice details. So you need to do some tweaking to figure out the best schedule for each image you generate, or at least the ones that need their level of detail adjusted. But ideally you should be spending countless hours of your life sculpting the perfect detail adjustment schedule for every image, cuz that's why we're here.
I'll soon provide specific examples addressing different scenarios and some of the techniques I've come up with. (note to self: move these to the wiki page)
## Installation
Open SD WebUI > Go to Extensions tab > Go to Available tab > Click Load from: > Find Detail Daemon > Click Install
Or Go to Install from URL tab > Paste this repo's URL into the first field > Click Install
Or go to your WebUI folder and manually clone this repo into your extensions folder:
`git clone "https://github.com/muerrilla/sd-webui-detail-daemon" extensions/sd-webui-detail-daemon`
## Getting Started
After installation you can find the extension in your txt2img and img2img tabs.

### Sliders:
The sliders (and that one checkbox) set the amount of adjustment (positive values → add detail, negative values → remove detail) and the sampling steps during which it is applied (i.e. the schedule). So the X axis of the graph is your sampling steps, normalized to the (0,1) range, and the Y axis is the amount of adjustment. The rest is pretty self-explanatory I think. Just drag things and look at the graph for changes.
### Numbers:
The three number inputs at the buttom are provided because sometimes the slider max/mins are too limiting.
### Modes:
The `cond` and `uncond` modes affect only their respective latents, while `both` affects both (duh!). The `cond` and `uncond` modes are less intense and also allow changes to be applied at earlier steps without diverging too far from the original generation, since the other latent stays intact.
There's also a minor twist: in the `both` mode if `detail amount` is positive both cond and uncond latents become more detailed. So the more detailed cond latent will try to push the generation towards more detail, while the more detailed uncond latent will try to push towards less detail. This causes more new features/artifacts to pop into the image in this mode.
### Tips:
I'll write up some proper docs on how best to set the parameters, as soon as possible. For now you gotta play around with the sliders and figure out how the shape of the schedule affects the image. I suggest you set your live preview update period to every frame, or every other frame, so you could see clearly what's going on at every step of the sampling process and how Detail Daemon affects it, till you get a good grasp of how this thing works.
## Notes:
- Doesn't support Compositional Diffusion (i.e. the AND syntax) properly. Specially if you have a batch size > 1 or negative weights in your prompts, and the mode is set to `cond` or `uncond`.
- It's probably impossible to use or very hard to control with few-step models (Turbo, Lightning, etc.). Edit: It's managable.
- It works with Forge (`cond` and `uncond` modes are not supported).
- It's not the same as AlignYourSteps, FreeU, etc.
- It is similar (in what it sets out to do, not in how it does it) to the [ReSharpen Extension](https://github.com/Haoming02/sd-webui-resharpen) by Haoming.111111123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313import os
import gradio as gr
import numpy as np
from tqdm import tqdm
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import modules.scripts as scripts
from modules.script_callbacks import on_cfg_denoiser, remove_callbacks_for_function, on_infotext_pasted
from modules.ui_components import InputAccordion
def parse_infotext(infotext, params):
try:
d = {}
for s in params['Detail Daemon'].split(','):
k, _, v = s.partition(':')
d[k.strip()] = v.strip()
params['Detail Daemon'] = d
except Exception:
pass
on_infotext_pasted(parse_infotext)
class Script(scripts.Script):
def title(self):
return "Detail Daemon"
def show(self, is_img2img):
return scripts.AlwaysVisible
def ui(self, is_img2img):
with InputAccordion(False, label="Detail Daemon", elem_id=self.elem_id('detail-daemon')) as gr_enabled:
with gr.Row():
with gr.Column(scale=2):
gr_amount_slider = gr.Slider(minimum=-1.00, maximum=1.00, step=.01, value=0.10, label="Detail Amount")
gr_start = gr.Slider(minimum=0.0, maximum=1.0, step=.01, value=0.2, label="Start")
gr_end = gr.Slider(minimum=0.0, maximum=1.0, step=.01, value=0.8, label="End")
gr_bias = gr.Slider(minimum=0.0, maximum=1.0, step=.01, value=0.5, label="Bias")
with gr.Column(scale=1, min_width=275):
preview = self.visualize(False, 0.2, 0.8, 0.5, 0.1, 1, 0, 0, 0, True)
gr_vis = gr.Plot(value=preview, elem_classes=['detail-daemon-vis'], show_label=False)
with gr.Accordion("More Knobs:", elem_classes=['detail-daemon-more-accordion'], open=False):
with gr.Row():
with gr.Column(scale=2):
with gr.Row():
gr_start_offset_slider = gr.Slider(minimum=-1.00, maximum=1.00, step=.01, value=0.00, label="Start Offset", min_width=60)
gr_end_offset_slider = gr.Slider(minimum=-1.00, maximum=1.00, step=.01, value=0.00, label="End Offset", min_width=60)
with gr.Row():
gr_exponent = gr.Slider(minimum=0.0, maximum=10.0, step=.05, value=1.0, label="Exponent", min_width=60)
gr_fade = gr.Slider(minimum=0.0, maximum=1.0, step=.05, value=0.0, label="Fade", min_width=60)
# Because the slider max and min are sometimes too limiting:
with gr.Row():
gr_amount = gr.Number(value=0.10, precision=4, step=.01, label="Amount", min_width=60)
gr_start_offset = gr.Number(value=0.0, precision=4, step=.01, label="Start Offset", min_width=60)
gr_end_offset = gr.Number(value=0.0, precision=4, step=.01, label="End Offset", min_width=60)
with gr.Column(scale=1, min_width=275):
gr_mode = gr.Dropdown(["both", "cond", "uncond"], value="uncond", label="Mode", show_label=True, min_width=60, elem_classes=['detail-daemon-mode'])
gr_smooth = gr.Checkbox(label="Smooth", value=True, min_width=60, elem_classes=['detail-daemon-smooth'])
gr.Markdown("## [Ⓗ Help](https://github.com/muerrilla/sd-webui-detail-daemon)", elem_classes=['detail-daemon-help'])
gr_amount_slider.release(None, gr_amount_slider, gr_amount, _js="(x) => x")
gr_amount.change(None, gr_amount, gr_amount_slider, _js="(x) => x")
gr_start_offset_slider.release(None, gr_start_offset_slider, gr_start_offset, _js="(x) => x")
gr_start_offset.change(None, gr_start_offset, gr_start_offset_slider, _js="(x) => x")
gr_end_offset_slider.release(None, gr_end_offset_slider, gr_end_offset, _js="(x) => x")
gr_end_offset.change(None, gr_end_offset, gr_end_offset_slider, _js="(x) => x")
vis_args = [gr_enabled, gr_start, gr_end, gr_bias, gr_amount, gr_exponent, gr_start_offset, gr_end_offset, gr_fade, gr_smooth]
for vis_arg in vis_args:
if isinstance(vis_arg, gr.components.Slider):
vis_arg.release(fn=self.visualize, show_progress=False, inputs=vis_args, outputs=[gr_vis])
else:
vis_arg.change(fn=self.visualize, show_progress=False, inputs=vis_args, outputs=[gr_vis])
def extract_infotext(d: dict, key, old_key):
if 'Detail Daemon' in d:
return d['Detail Daemon'].get(key)
return d.get(old_key)
self.infotext_fields = [
(gr_enabled, lambda d: True if ('Detail Daemon' in d or 'DD_enabled' in d) else False),
(gr_mode, lambda d: extract_infotext(d, 'mode', 'DD_mode')),
(gr_amount, lambda d: extract_infotext(d, 'amount', 'DD_amount')),
(gr_start, lambda d: extract_infotext(d, 'st', 'DD_start')),
(gr_end, lambda d: extract_infotext(d, 'ed', 'DD_end')),
(gr_bias, lambda d: extract_infotext(d, 'bias', 'DD_bias')),
(gr_exponent, lambda d: extract_infotext(d, 'exp', 'DD_exponent')),
(gr_start_offset, lambda d: extract_infotext(d, 'st_offset', 'DD_start_offset')),
(gr_end_offset, lambda d: extract_infotext(d, 'ed_offset', 'DD_end_offset')),
(gr_fade, lambda d: extract_infotext(d, 'fade', 'DD_fade')),
(gr_smooth, lambda d: extract_infotext(d, 'smooth', 'DD_smooth')),
]
return [gr_enabled, gr_mode, gr_start, gr_end, gr_bias, gr_amount, gr_exponent, gr_start_offset, gr_end_offset, gr_fade, gr_smooth]
def process(self, p, enabled, mode, start, end, bias, amount, exponent, start_offset, end_offset, fade, smooth):
enabled = getattr(p, "DD_enabled", enabled)
mode = getattr(p, "DD_mode", mode)
amount = getattr(p, "DD_amount", amount)
start = getattr(p, "DD_start", start)
end = getattr(p, "DD_end", end)
bias = getattr(p, "DD_bias", bias)
exponent = getattr(p, "DD_exponent", exponent)
start_offset = getattr(p, "DD_start_offset", start_offset)
end_offset = getattr(p, "DD_end_offset", end_offset)
fade = getattr(p, "DD_fade", fade)
smooth = getattr(p, "DD_smooth", smooth)
if enabled:
if p.sampler_name == "DPM adaptive":
tqdm.write(f'\033[33mWARNING:\033[0m Detail Daemon does not work with {p.sampler_name}')
return
# Restart can be handled better, later maybe
actual_steps = (p.steps * 2 - 1) if p.sampler_name in ['DPM++ SDE', 'DPM++ 2S a', 'Heun', 'DPM2', 'DPM2 a', 'Restart'] else p.steps
self.schedule = self.make_schedule(actual_steps, start, end, bias, amount, exponent, start_offset, end_offset, fade, smooth)
self.mode = mode
self.cfg_scale = p.cfg_scale
self.batch_size = p.batch_size
on_cfg_denoiser(self.denoiser_callback)
self.callback_added = True
p.extra_generation_params['Detail Daemon'] = f'mode:{mode},amount:{amount},st:{start},ed:{end},bias:{bias},exp:{exponent},st_offset:{start_offset},ed_offset:{end_offset},fade:{fade},smooth:{1 if smooth else 0}'
tqdm.write('\033[32mINFO:\033[0m Detail Daemon is enabled')
else:
if hasattr(self, 'callback_added'):
remove_callbacks_for_function(self.denoiser_callback)
delattr(self, 'callback_added')
# tqdm.write('\033[90mINFO: Detail Daemon callback removed\033[0m')
def before_process_batch(self, p, *args, **kwargs):
self.is_hires = False
def postprocess(self, p, processed, *args):
if hasattr(self, 'callback_added'):
remove_callbacks_for_function(self.denoiser_callback)
delattr(self, 'callback_added')
# tqdm.write('\033[90mINFO: Detail Daemon callback removed\033[0m')
def before_hr(self, p, *args):
self.is_hires = True
enabled = args[0]
if enabled:
tqdm.write(f'\033[33mINFO:\033[0m Detail Daemon does not work during Hires Fix')
def denoiser_callback(self, params):
if self.is_hires:
return
idx = params.denoiser.step
multiplier = self.schedule[idx] * .1
mode = self.mode
if params.sigma.size(0) == 1:
mode = "both"
if idx == 0:
tqdm.write(f'\033[33mWARNING:\033[0m Forge does not support `cond` and `uncond` modes, using `both` instead')
if mode == "cond":
for i in range(self.batch_size):
params.sigma[i] *= 1 - multiplier
elif mode == "uncond":
for i in range(self.batch_size):
params.sigma[self.batch_size + i] *= 1 + multiplier
else:
params.sigma *= 1 - multiplier * self.cfg_scale
def make_schedule(self, steps, start, end, bias, amount, exponent, start_offset, end_offset, fade, smooth):
start = min(start, end)
mid = start + bias * (end - start)
multipliers = np.zeros(steps)
start_idx, mid_idx, end_idx = [int(round(x * (steps - 1))) for x in [start, mid, end]]
start_values = np.linspace(0, 1, mid_idx - start_idx + 1)
if smooth:
start_values = 0.5 * (1 - np.cos(start_values * np.pi))
start_values = start_values ** exponent
if start_values.any():
start_values *= (amount - start_offset)
start_values += start_offset
end_values = np.linspace(1, 0, end_idx - mid_idx + 1)
if smooth:
end_values = 0.5 * (1 - np.cos(end_values * np.pi))
end_values = end_values ** exponent
if end_values.any():
end_values *= (amount - end_offset)
end_values += end_offset
multipliers[start_idx:mid_idx+1] = start_values
multipliers[mid_idx:end_idx+1] = end_values
multipliers[:start_idx] = start_offset
multipliers[end_idx+1:] = end_offset
multipliers *= 1 - fade
return multipliers
def visualize(self, enabled, start, end, bias, amount, exponent, start_offset, end_offset, fade, smooth):
try:
steps = 50
values = self.make_schedule(steps, start, end, bias, amount, exponent, start_offset, end_offset, fade, smooth)
mean = sum(values)/steps
peak = np.clip(max(abs(values)), -1, 1)
if start > end:
start = end
mid = start + bias * (end - start)
opacity = .1 + (1 - fade) * 0.7
plot_color = (0.5, 0.5, 0.5, opacity) if not enabled else ((1 - peak)**2, 1, 0, opacity) if mean >= 0 else (1, (1 - peak)**2, 0, opacity)
plt.rcParams.update({
"text.color": plot_color,
"axes.labelcolor": plot_color,
"axes.edgecolor": plot_color,
"figure.facecolor": (0.0, 0.0, 0.0, 0.0),
"axes.facecolor": (0.0, 0.0, 0.0, 0.0),
"ytick.labelsize": 6,
"ytick.labelcolor": plot_color,
"ytick.color": plot_color,
})
fig, ax = plt.subplots(figsize=(2.15, 2.00), layout="constrained")
ax.plot(range(steps), values, color=plot_color)
ax.axhline(y=0, color=plot_color, linestyle='dotted')
ax.axvline(x=mid * (steps - 1), color=plot_color, linestyle='dotted')
ax.tick_params(right=False, color=plot_color)
ax.set_xticks([i * (steps - 1) / 10 for i in range(10)][1:])
ax.set_xticklabels([])
ax.set_ylim([-1, 1])
ax.set_xlim([0, steps-1])
plt.close()
self.last_vis = fig
return fig
except Exception:
if self.last_vis is not None:
return self.last_vis
return
def xyz_support():
for scriptDataTuple in scripts.scripts_data:
if os.path.basename(scriptDataTuple.path) == 'xyz_grid.py':
xy_grid = scriptDataTuple.module
def confirm_mode(p, xs):
for x in xs:
if x not in ['both', 'cond', 'uncond']:
raise RuntimeError(f'Invalid Detail Daemon Mode: {x}')
mode = xy_grid.AxisOption(
'[Detail Daemon] Mode',
str,
xy_grid.apply_field('DD_mode'),
confirm=confirm_mode
)
amount = xy_grid.AxisOption(
'[Detail Daemon] Amount',
float,
xy_grid.apply_field('DD_amount')
)
start = xy_grid.AxisOption(
'[Detail Daemon] Start',
float,
xy_grid.apply_field('DD_start')
)
end = xy_grid.AxisOption(
'[Detail Daemon] End',
float,
xy_grid.apply_field('DD_end')
)
bias = xy_grid.AxisOption(
'[Detail Daemon] Bias',
float,
xy_grid.apply_field('DD_bias')
)
exponent = xy_grid.AxisOption(
'[Detail Daemon] Exponent',
float,
xy_grid.apply_field('DD_exponent')
)
start_offset = xy_grid.AxisOption(
'[Detail Daemon] Start Offset',
float,
xy_grid.apply_field('DD_start_offset')
)
end_offset = xy_grid.AxisOption(
'[Detail Daemon] End Offset',
float,
xy_grid.apply_field('DD_end_offset')
)
fade = xy_grid.AxisOption(
'[Detail Daemon] Fade',
float,
xy_grid.apply_field('DD_fade')
)
xy_grid.axis_options.extend([
mode,
amount,
start,
end,
bias,
exponent,
start_offset,
end_offset,
fade,
])
try:
xyz_support()
except Exception as e:
print(f'Error trying to add XYZ plot options for Detail Daemon', e)1234567891011121314151617181920.detail-daemon-more-accordion {
margin-top: 1em !important;
}
.detail-daemon-mode {
margin-left: 3em !important;
width: 75% !important;
}
.detail-daemon-smooth {
margin-left: 3em !important;
}
.detail-daemon-vis {
margin: auto !important;
}
.detail-daemon-help {
margin: auto 1.5em !important;
}1ko_fi: haoming1112__pycache__
styles.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145### v2.3.2 - 2024 Nov.06
- Linting *(`internal`)*
### v2.3.1 - 2024 Nov.04
- Implement **Range** Settings
### v2.3.0 - 2024 Sep.20
- Refactor
### v2.2.6 - 2024 Sep.18
- Allow disabling `do_not_save_to_config` to use **Defaults**
### v2.2.5 - 2024 Aug.30
- Correct Y'CbCr **Conversion**?
### v2.2.4 - 2024 Aug.28
- Optimization *(`internal`)*
- Improve Color **Accuracy** ~~Slightly~~
### v2.2.3 - 2024 Aug.27
- Lib *(`internal`)*
### v2.2.2 - 2024 Aug.27
- Fix **Color Picker** for Gradio **4**
### v2.2.1 - 2024 Aug.02
- `@torch.inference_mode()`
### v2.2.0 - 2024 Jul.03
- Add `Adv.` in **Styles Presets**
- Improve **Consts** Logics *(`internal`)*
### v2.1.0 - 2024 Jul.03
- Support **Randomize** Forever
### v2.0.3 - 2024 Jun.25
- Format
### v2.0.2 - 2024 Jun.24
- Bug Fix
### v2.0.1 - 2024 Mar.07
- Support **ADetailer**
### v2.0.0 - 2024 Mar.05
- Improved Logics
### v2.0.epsilon - 2024 Mar.04
- Improved Logics
### v2.0.delta - 2024 Mar.04
- Support **SDXL**
### v2.0.gamma - 2024 Mar.01
- Major **Rewrite** & **Optimization**
### v2.0.beta - 2024 Feb.29
- Revert Sampler **Hook** *(`internal`)*
### v2.0.alpha - 2024 Feb.29
- Changed Sampler **Hook** *(`internal`)*
- Removed **LFS** *(`GitHub`)*
### v1.5.1 - 2023 Dec.03
- Bug Fix by. **catboxanon**
### v1.5.0 - 2023 Nov.08
- Rewrote **Callback** logic *(`internal`)*
### v1.4.10 - 2023 Nov.01
- Better **Hires. fix** logic
### v1.4.9 - 2023 Nov.01
- Improve Sliders values refresh
### v1.4.8 - 2023 Nov.01
- Removed "**magic numbers**"
### v1.4.7 - 2023 Nov.01
- Removed **Skip** parameter
### v1.4.6 - 2023 Sep.19
- Add **HDR** Script
### v1.4.5 - 2023 Sep.13
- Bug Fix for Color Wheel in `img2img`
- Minor Formatting
### v1.4.4 - 2023 Sep.13
- Add **Infotext** Support by. **catboxanon**
### v1.4.3 - 2023 Sep.13
- Improve **Color Wheel** Functionality by. **catboxanon**
### v1.4.2 - 2023 Sep.11
- Fix the Reset and Randomize buttons for the new Contrast algorithm
### v1.4.1 - 2023 Sep.11
- New **Contrast** algorithm
### v1.4.0 - 2023 Jul.11
- Implement **Scaling** algorithm
### v1.3.5 - 2023 Jul.11
- Implement **Color Picker**
### v1.3.4 - 2023 Jul.08
- Implement **Metadata**
### v1.3.3 - 2023 Jul.07
- Color Wheel now works at (0, 0, 0)
- Style/Randomize/Reset now updates Color Wheel
### v1.3.2 - 2023 Jul.07
- Implement **Color Wheel**
- Finally added `changelog`
### v1.3.1 - 2023 Jul.06
- Bug Fix
### v1.3.0 - 2023 Jul.06
- Implement **Style Presets**
- Separate logics into different scripts
### v1.2.1 - 2023 Jul.05
- Add **Randomize** function
- Add **Reset** function
### v1.2.0 - 2023 Jul.03
- Implement multiple **Noise** algorithms
### v1.1.3 - 2023 Jun.26
- Automatically refresh outdated Sliders values
### v1.1.2 - 2023 Jun.23
- Bug Fix
### v1.1.1 - 2023 Jun.22
- **Batch** Support
### v1.1.0 - 2023 Jun.21
- **X/Y/Z Plot** Support
### v1.0.0 - 2023 Jun.20
- Extension **Released**!123456789101112131415161718192021MIT License
Copyright (c) 2024 Haoming
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375# SD Webui Vectorscope CC
This is an Extension for the [Automatic1111 Webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui), which performs a kind of **Offset Noise** natively during inference, allowing you to adjust the brightness, contrast, and color of the generations.
> Also supports both old & new [Forge](https://github.com/lllyasviel/stable-diffusion-webui-forge)
## Example Images
<p align="center">
<img src="samples/00.jpg" width=256><br>
<code>Base Image w/o Extension</code>
</p>
<details>
<summary>Infotext</summary>
- **Checkpoint:** [realisticVisionV51](https://civitai.com/models/4201?modelVersionId=130072)
- **Positive Prompt:** `(high quality, best quality), a 4k cinematic photo of a gentleman in suit, street in a city at night, (depth of field, bokeh)`
- **Negative Prompt:** `(low quality, worst quality:1.2), [EasyNegative, EasyNegativeV2]`
```cpp
Steps: 32, Sampler: DPM++ 2M Karras, CFG scale: 7.5, Seed: 3709157017, Size: 512x512, Denoising strength: 0.5
Clip skip: 2, Token merging ratio: 0.2, Token merging ratio hr: 0.2, RNG: CPU, NGMS: 4
Hires upscale: 2, Hires steps: 16, Hires upscaler: 2xNomosUni_esrgan_multijpg
```
</details>
<table>
<thead>
<tr align="center">
<td><b>Vibrant</b></td>
<td><b>Cold</b></td>
<td><b>"Movie when Mexico"</b></td>
</tr>
</thead>
<tbody>
<tr align="center">
<td><img src="samples/01.jpg" width=512></td>
<td><img src="samples/02.jpg" width=512></td>
<td><img src="samples/03.jpg" width=512></td>
</tr>
<tr align="left">
<td>
<ul>
<li><b>Alt:</b> <code>True</code></li>
<li><b>Saturation:</b> <code>1.75</code></li>
<li><b>Noise:</b> <code>Ones</code></li>
<li><b>Scaling:</b> <code>1 - Cos</code></li>
</ul>
</td>
<td>
<ul>
<li><b>Brightness:</b> <code>-5.0</code></li>
<li><b>Contrast:</b> <code>2.5</code></li>
<li><b>Saturation:</b> <code>0.75</code></li>
<li><b>R:</b> <code>-3.0</code></li>
<li><b>B:</b> <code>3.0</code></li>
<li><b>Noise:</b> <code>Ones</code></li>
<li><b>Scaling:</b> <code>1 - Sin</code></li>
</ul>
</td>
<td>
<ul>
<li><b>Brightness:</b> <code>2.5</code></li>
<li><b>Contrast:</b> <code>-2.5</code></li>
<li><b>Saturation:</b> <code>1.25</code></li>
<li><b>R:</b> <code>1.5</code></li>
<li><b>G:</b> <code>3.0</code></li>
<li><b>B:</b> <code>-4.0</code></li>
<li><b>Noise:</b> <code>Ones</code></li>
<li><b>Scaling:</b> <code>1 - Sin</code></li>
</ul>
</td>
</tr>
</tbody>
</table>
## How to Use
> **Note:** Since this Extension modifies the underlying latent tensor, the composition may change drastically depending on the parameters
### Basic Parameters
- **Enable:** Enable the Extension 💀
- **Alt:** Cause the Extension effects to be stronger
<details>
<summary><i>Technical Detail</i></summary>
- This parameter makes the Extension modify the `denoised` Tensor instead of the `x` Tensor
</details>
- **Brightness**, **Contrast**, **Saturation**: Adjust the overall `brightness` / `contrast` / `saturation` of the image
#### Color Channels
<table>
<thead align="center">
<tr>
<td><b>Channel</b></td>
<td><b>Lower</b></td>
<td><b>Higher</b></td>
</tr>
</thead>
<tbody align="center">
<tr>
<td><b>R</b></td>
<td>Cyan</td>
<td>Red</td>
</tr>
<tr>
<td><b>G</b></td>
<td>Magenta</td>
<td>Green</td>
</tr>
<tr>
<td><b>B</b></td>
<td>Yellow</td>
<td>Blue</td>
</tr>
</tbody>
</table>
- The Extension also comes with a Color Wheel for visualization, which you can also click on to pick a color directly
> The color picker isn't 100% accurate due to multiple layers of conversions...
#### Style Presets
- To apply a Style, select from the `Dropdown` then click **Apply Style**
- To save a Style, enter a name in the `Textbox` then click **Save Style**
- To delete a Style, enter the name in the `Textbox` then click **Delete Style**
- *Style that was deleted is still in the `styles.json` in case you wish to retrieve it*
- Click **Refresh Style** to update the `Dropdown` if you edited the `styles.json` manually
<blockquote>
You can also find pre-made Styles by the community available online<br>
<ul>
<li><b>eg.</b>
The <a href="https://raw.githubusercontent.com/sandner-art/Photomatix/refs/heads/main/PX-Vectorscope-CC-Styles/styles.json">Photomatix</a>
Styles <i>(right click on the link, click <code>Save link as</code>, then save the <code>.json</code> file into the
<b>sd-webui-vectorscope-cc</b> extension folder)</i>
</li>
</ul>
</blockquote>
### Advanced Parameters
- **Process Hires. fix:** Enable this option to process during the **Hires. fix** phase too
- By default, this Extension only functions during the regular phase of the `txt2img` mode
- **Process ADetailer:** Enable this option to process during the **[ADetailer](https://github.com/Bing-su/adetailer)** phase too
- Will usually cause a square of inconsistent colors
- **Randomize using Seed:** Enable this option to use the current generation `seed` to randomize the basic parameters
- Randomized results will be printed in the console
#### Noise Settings
> let **`x`** denote the latent Tensor ; let **`y`** denote the operations
- **Straight:** All operations are calculated on the same Tensor
- `x += x * y`
- **Cross:** All operations are calculated on the Tensor opposite of the `Alt.` setting
- `x += x' * y`
- **Ones:** All operations are calculated on a Tensor filled with ones
- `x += 1 * y`
- **N.Random:** All operations are calculated on a Tensor filled with random values in normal distribution
- `x += randn() * y`
- **U.Random:** All operations are calculated on a Tensor filled with random values in uniform distribution
- `x += rand() * y`
- **Multi-Res:** All operations are calculated on a Tensor generated with multi-res noise algorithm
- `x += multires() * y`
- **Abs:** Calculate using the absolute values of the chosen Tensors instead
- `x += abs(F) * y`
<p align="center">
<img src="samples/method.jpg">
</p>
<details>
<summary>Infotext</summary>
- **Checkpoint:** [realisticVisionV51](https://civitai.com/models/4201?modelVersionId=130072)
- **Positive Prompt:** `(high quality, best quality), a 4k photo of a cute dog running in the snow, mountains, day, (depth of field, bokeh)`
- **Negative Prompt:** `(low quality, worst quality:1.2), [EasyNegative, EasyNegativeV2]`
- **Brightness:** `2.5`
- **Contrast:** `2.5`
- **Alt:** `True`
- **Scaling:** `1 - Cos`
```cpp
Steps: 24, Sampler: DPM++ 2M Karras, CFG scale: 7.5, Seed: 1257068736, Size: 512x512, Denoising strength: 0.5
Clip skip: 2, Token merging ratio: 0.2, Token merging ratio hr: 0.2, RNG: CPU, NGMS: 4
Hires upscale: 1.5, Hires steps: 16, Hires upscaler: 2xNomosUni_esrgan_multijpg
```
</details>
#### Scaling Settings
By default, this Extension offsets the noise by the same amount every step. But depending on the `Sampler` and `Scheduler` used, and whether `Alt.` was enabled or not, the effects might be too strong during the early or the later phase of the process, which in turn causes artifacts.
- **Flat:** Default behavior
- **Cos:** Cosine scaling `(High -> Low)`
- **Sin:** Sine scaling `(Low -> High)`
- **1 - Cos:** `(Low -> High)`
- **1 - Sin:** `(High -> Low)`
<p align="center">
<img src="samples/scaling.jpg">
</p>
<details>
<summary>Infotext</summary>
- **Checkpoint:** [realisticVisionV51](https://civitai.com/models/4201?modelVersionId=130072)
- **Positive Prompt:** `(high quality, best quality), a 4k photo of a cute cat standing at a flower field in a park, day, (depth of field, bokeh)`
- **Negative Prompt:** `(low quality, worst quality:1.2), [EasyNegative, EasyNegativeV2]`
- **Alt:** `True`
- **Noise:** `Straight Abs.`
```cpp
Steps: 24, Sampler: DPM++ 2M Karras, CFG scale: 7.5, Seed: 3515074713, Size: 512x512, Denoising strength: 0.5
Clip skip: 2, Token merging ratio: 0.2, Token merging ratio hr: 0.2, RNG: CPU, NGMS: 4
Hires upscale: 1.5, Hires steps: 12, Hires upscaler: 2xNomosUni_esrgan_multijpg
```
</details>
### Buttons
- **Reset:** Reset all `Basic` and `Advanced` parameters to the default values
- **Randomize:** Randomize the `Brightness`, `Contrast`, `Saturation`, `R`, `G`, `B` parameters
## Settings
> The following settings are in the **Vectorscope CC** section under the **Stable Diffusion** category of the **Settings** tab
- Append the parameters to the infotext
- Disable `do_not_save_to_config` to use the Webui **Defaults** functionality
- Set the `minimum` and `maximum` range for each parameter
## Roadmap
- [X] Extension Released!
- [X] Add Support for **X/Y/Z Plot**
- [X] Implement different **Noise** functions
- [X] Implement **Randomize** button
- [X] Implement **Style** Presets
- [X] Implement **Color Wheel** & **Color Picker**
- [X] Implement better scaling algorithms
- [X] Add API Docs
- [X] Append Parameters to Infotext
- [X] Improved Infotext Support *(by. [catboxanon](https://github.com/catboxanon))*
- [X] Add **HDR** Script
- [X] Add Support for **SDXL**
- [ ] Implement Gradient features
## API
You can use this Extension via [API](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API) by adding an entry to the `alwayson_scripts` of your payload. An [example](samples/api_example.json) is provided. The `args` are sent in the following order in an `array`:
<table>
<thead>
<tr align="center">
<td><b>Parameter</b></td>
<td><b>Type</b></td>
</tr>
</thead>
<tbody>
<tr align="center">
<td>Enable</td>
<td><code>bool</code></td>
</tr>
<tr align="center">
<td>Alt.</td>
<td><code>bool</code></td>
</tr>
<tr align="center">
<td>Brightness</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>Contrast</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>Saturation</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>R</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>G</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>B</td>
<td><code>float</code></td>
</tr>
<tr align="center">
<td>Hires. fix</td>
<td><code>bool</code></td>
</tr>
<tr align="center">
<td>ADetailer</td>
<td><code>bool</code></td>
</tr>
<tr align="center">
<td>Randomize</td>
<td><code>bool</code></td>
</tr>
<tr align="center">
<td>Noise Method</td>
<td><code>str</code></td>
</tr>
<tr align="center">
<td>Scaling</td>
<td><code>str</code></td>
</tr>
</tbody>
</table>
## Known Issues
- In rare occasions, this Extension has little effects when used with certain **LoRA**s
- Works better / worse with certain `Samplers`
<!--- *(See [Wiki](https://github.com/Haoming02/sd-webui-vectorscope-cc/wiki/Vectorscope-CC-Wiki#effects-with-different-samplers))* --->
## HDR
> [Discussion Thread](https://github.com/Haoming02/sd-webui-vectorscope-cc/issues/16)
In the **Script** `Dropdown` at the bottom, there is now a new **`High Dynamic Range`** option:
- This script will generate multiple images *("Brackets")* of varying brightness, then merge them into 1 HDR image
- **(Recommended)** Use a deterministic sampler and high enough steps. `Euler` *(**not** `Euler a`)* works well in my experience
#### Options
- **Brackets:** The numer of images to generate
- **Gaps:** The brightness difference between each image
- **Automatically Merge:** When enabled, this will merge the images using an `OpenCV` algorithm and save to the `HDR` folder in the `outputs` folder
- Disable this if you want to merge them yourself using better external program
<hr>
<details>
<summary>Offset Noise TL;DR</summary>
The most common *version* of **Offset Noise** you may have heard of is from this [blog post](https://www.crosslabs.org/blog/diffusion-with-offset-noise), where it was discovered that the noise functions used during **training** were flawed, causing `Stable Diffusion` to always generate images with an average of `0.5` *(**ie.** grey)*.
> **ie.** Even if you prompt for dark/night or bright/snow, the average of the image is still "grey"
> [Technical Explanations](https://youtu.be/cVxQmbf3q7Q)
However, this Extension instead tries to offset the latent noise during the **inference** phase. Therefore, you do not need to use models that were specially trained, as this can work on any model.
</details>
<details>
<summary>How does this work?</summary>
After reading through and messing around with the code, I found out that it is possible to directly modify the Tensors representing the latent noise used by the Stable Diffusion process.
The dimensions of the Tensors is `(X, 4, H / 8, W / 8)`, which represents **X** batch of noise images, with **4** channels, each with **(W / 8) x (H / 8)** values
> **eg.** Generating a single 512x768 image will create a Tensor of size (1, 4, 96, 64)
Then, I tried to play around with the values of each channel and ended up discovering these relationships. Essentially, the 4 channels correspond to the **CMYK** color format for `SD1` *(**Y'CbCr** for `SDXL`)*, hence why you can control the brightness as well as the colors.
</details>
<hr>
#### Vectorscope?
The Extension is named this way because the color interactions remind me of the `Vectorscope` found in **Premiere Pro**'s **Lumetri Color**. Those who are experienced in Color Correction should be rather familiar with this Extension.
<p align="center"><img src="scripts/vectorscope.png" width=256></p>
<sup>~~Yes. I'm aware that it's just how digital colors work in general.~~</sup>
<sup>~~We've come full **circle** *(\*ba dum tss)* now that a Color Wheel is actually added.~~</sup>1111123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128class VectorscopeCC {
static dot = { 'txt': undefined, 'img': undefined };
/**
* @param {number} r @param {number} g @param {number} b
* @param {string} mode "txt" | "img"
*/
static updateCursor(r, g, b, mode) {
const mag = Math.abs(r) + Math.abs(g) + Math.abs(b);
let condX, condY;
if (mag < Number.EPSILON) {
condX = 0.0;
condY = 0.0;
} else {
condX = 25 * Math.sqrt(r * r + g * g + b * b) * (r * -0.5 + g * -0.5 + b * 1.0) / mag;
condY = 25 * Math.sqrt(r * r + g * g + b * b) * (r * -0.866 + g * 0.866 + b * 0.0) / mag;
}
this.dot[mode].style.left = `calc(50% + ${condX - 12}px)`;
this.dot[mode].style.top = `calc(50% + ${condY - 12}px)`;
}
/**
* @param {HTMLImageElement} wheel
* @param {HTMLInputElement[]} sliders
* @param {HTMLImageElement} dot
*/
static registerPicker(wheel, sliders, dot) {
['mousemove', 'click'].forEach((event) => {
wheel.addEventListener(event, (e) => {
e.preventDefault();
if (e.type === 'mousemove' && e.buttons != 1)
return;
const rect = e.target.getBoundingClientRect();
const p_rect = e.target.parentNode.getBoundingClientRect();
const shift = (p_rect.width - rect.width) / 2.0;
dot.style.left = `calc(${e.clientX - rect.left}px - 12px + ${shift}px)`;
dot.style.top = `calc(${e.clientY - rect.top}px - 12px)`;
const x = ((e.clientX - rect.left) - 100.0) / 25;
const y = ((e.clientY - rect.top) - 100.0) / 25;
let r = -0.077 * (4.33 * x + 7.5 * y);
let g = y / 0.866 + r;
let b = x + 0.5 * r + 0.5 * g;
const mag = Math.sqrt(r * r + g * g + b * b);
const len = Math.abs(r) + Math.abs(g) + Math.abs(b);
r = (r / mag * len).toFixed(2);
g = (g / mag * len).toFixed(2);
b = (b / mag * len).toFixed(2);
sliders[0][0].value = r;
sliders[0][1].value = r;
sliders[1][0].value = g;
sliders[1][1].value = g;
sliders[2][0].value = b;
sliders[2][1].value = b;
});
});
['mouseleave', 'mouseup'].forEach((event) => {
wheel.addEventListener(event, () => {
updateInput(sliders[0][0]);
updateInput(sliders[1][0]);
updateInput(sliders[2][0]);
});
});
}
}
onUiLoaded(() => {
['txt', 'img'].forEach((mode) => {
const container = document.getElementById(`cc-colorwheel-${mode}`);
container.style.height = '200px';
container.style.width = '200px';
const wheel = container.querySelector('img');
container.insertBefore(wheel, container.firstChild);
while (container.firstChild !== container.lastChild)
container.lastChild.remove();
wheel.ondragstart = (e) => { e.preventDefault(); return false; };
wheel.id = `cc-img-${mode}`;
const sliders = [
document.getElementById(`cc-r-${mode}`).querySelectorAll('input'),
document.getElementById(`cc-g-${mode}`).querySelectorAll('input'),
document.getElementById(`cc-b-${mode}`).querySelectorAll('input'),
];
const temp = document.getElementById(`cc-temp-${mode}`);
const dot = temp.querySelector('img');
dot.style.left = 'calc(50% - 12px)';
dot.style.top = 'calc(50% - 12px)';
dot.id = `cc-dot-${mode}`;
container.appendChild(dot);
temp.remove();
VectorscopeCC.dot[mode] = dot;
VectorscopeCC.registerPicker(wheel, sliders, dot);
});
const config = document.getElementById("setting_cc_no_defaults").querySelector('input[type=checkbox]');
if (config.checked)
return;
setTimeout(() => {
['txt', 'img'].forEach((mode) => {
const r = document.getElementById(`cc-r-${mode}`).querySelector("input").value;
const g = document.getElementById(`cc-g-${mode}`).querySelector("input").value;
const b = document.getElementById(`cc-b-${mode}`).querySelector("input").value;
VectorscopeCC.updateCursor(r, g, b, mode);
});
}, 100);
});1234"""
Author: Haoming02
License: MIT
"""11123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180from modules.sd_samplers_kdiffusion import KDiffusionSampler
from modules.script_callbacks import on_script_unloaded, on_ui_settings
from functools import wraps
from random import random
import torch
from .scaling import apply_scaling
from .settings import settings
class NoiseMethods:
@staticmethod
def get_delta(latent: torch.Tensor) -> torch.Tensor:
mean = torch.mean(latent)
return torch.sub(latent, mean)
@staticmethod
def to_abs(latent: torch.Tensor) -> torch.Tensor:
return torch.abs(latent)
@staticmethod
def zeros(latent: torch.Tensor) -> torch.Tensor:
return torch.zeros_like(latent)
@staticmethod
def ones(latent: torch.Tensor) -> torch.Tensor:
return torch.ones_like(latent)
@staticmethod
def gaussian_noise(latent: torch.Tensor) -> torch.Tensor:
return torch.rand_like(latent)
@staticmethod
def normal_noise(latent: torch.Tensor) -> torch.Tensor:
return torch.randn_like(latent)
@staticmethod
@torch.inference_mode()
def multires_noise(
latent: torch.Tensor,
use_zero: bool,
iterations: int = 10,
discount: float = 0.8,
):
"""
Credit: Kohya_SS
https://github.com/kohya-ss/sd-scripts/blob/v0.8.5/library/custom_train_functions.py#L448
"""
noise = NoiseMethods.zeros(latent) if use_zero else NoiseMethods.ones(latent)
device = latent.device
b, c, w, h = noise.shape
upsampler = torch.nn.Upsample(size=(w, h), mode="bilinear").to(device)
for i in range(iterations):
r = random() * 2 + 2
wn = max(1, int(w / (r**i)))
hn = max(1, int(h / (r**i)))
noise += upsampler(torch.randn(b, c, wn, hn).to(device)) * discount**i
if wn == 1 or hn == 1:
break
return noise / noise.std()
def RGB2CbCr(r: float, g: float, b: float) -> tuple[float, float]:
"""Convert RGB channels into YCbCr for SDXL"""
cb = -0.17 * r - 0.33 * g + 0.5 * b
cr = 0.5 * r - 0.42 * g - 0.08 * b
return cb, cr
original_callback = KDiffusionSampler.callback_state
@torch.no_grad()
@torch.inference_mode()
@wraps(original_callback)
def cc_callback(self, d):
if not self.vec_cc["enable"]:
return original_callback(self, d)
if getattr(self.p, "is_hr_pass", False) and not self.vec_cc["doHR"]:
return original_callback(self, d)
if getattr(self.p, "_ad_inner", False) and not self.vec_cc["doAD"]:
return original_callback(self, d)
is_xl: bool = self.p.sd_model.is_sdxl
mode = str(self.vec_cc["mode"])
method = str(self.vec_cc["method"])
source: torch.Tensor = d[mode]
target = None
if "Straight" in method:
target = d[mode].detach().clone()
elif "Cross" in method:
target = d["x" if mode == "denoised" else "denoised"].detach().clone()
elif "Multi-Res" in method:
target = NoiseMethods.multires_noise(d[mode], "Abs" in method)
elif method == "Ones":
target = NoiseMethods.ones(d[mode])
elif method == "N.Random":
target = NoiseMethods.normal_noise(d[mode])
elif method == "U.Random":
target = NoiseMethods.gaussian_noise(d[mode])
else:
raise ValueError
if "Abs" in method:
target = NoiseMethods.to_abs(target)
batchSize = int(d[mode].size(0))
bri, con, sat, r, g, b = apply_scaling(
self.vec_cc["scaling"],
d["i"],
self.vec_cc["step"],
self.vec_cc["bri"],
self.vec_cc["con"],
self.vec_cc["sat"],
self.vec_cc["r"],
self.vec_cc["g"],
self.vec_cc["b"],
)
if not is_xl:
for i in range(batchSize):
# Brightness
source[i][0] += target[i][0] * bri
# Contrast
source[i][0] += NoiseMethods.get_delta(source[i][0]) * con
# R
source[i][2] -= target[i][2] * r
# G
source[i][1] += target[i][1] * g
# B
source[i][3] -= target[i][3] * b
# Saturation
source[i][2] *= sat
source[i][1] *= sat
source[i][3] *= sat
else:
cb, cr = RGB2CbCr(r, g, b)
for i in range(batchSize):
# Brightness
source[i][0] += target[i][0] * bri
# Contrast
source[i][0] += NoiseMethods.get_delta(source[i][0]) * con
# CbCr
source[i][1] -= target[i][1] * cr
source[i][2] -= target[i][2] * cb
# Saturation
source[i][1] *= sat
source[i][2] *= sat
return original_callback(self, d)
def restore_callback():
KDiffusionSampler.callback_state = original_callback
def hook_callbacks():
KDiffusionSampler.callback_state = cc_callback
on_script_unloaded(restore_callback)
on_ui_settings(settings)123456789101112131415161718192021222324252627from modules import scripts
import gradio as gr
import os
WHEEL = os.path.join(scripts.basedir(), "scripts", "vectorscope.png")
DOT = os.path.join(scripts.basedir(), "scripts", "dot.png")
def create_colorpicker(is_img: bool):
m: str = "img" if is_img else "txt"
whl = gr.Image(
value=WHEEL,
interactive=False,
container=False,
elem_id=f"cc-colorwheel-{m}",
)
dot = gr.Image(
value=DOT,
interactive=False,
container=False,
elem_id=f"cc-temp-{m}",
)
whl.do_not_save_to_config = True
dot.do_not_save_to_config = True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849from modules.shared import opts
import random
class Param:
def __init__(self, minimum: float, maximum: float, default: float):
self.minimum = minimum
self.maximum = maximum
self.default = default
def rand(self) -> float:
return round(random.uniform(self.minimum, self.maximum), 2)
Brightness: Param
Contrast: Param
Saturation: Param
Color: Param
def init():
global Brightness
Brightness = Param(
getattr(opts, "cc_brightness_min", -5.0),
getattr(opts, "cc_brightness_max", 5.0),
0.0,
)
global Contrast
Contrast = Param(
getattr(opts, "cc_contrast_min", -5.0),
getattr(opts, "cc_contrast_max", 5.0),
0.0,
)
global Saturation
Saturation = Param(
getattr(opts, "cc_saturation_min", 0.25),
getattr(opts, "cc_saturation_max", 1.75),
1.0,
)
global Color
Color = Param(
getattr(opts, "cc_color_min", -4.0),
getattr(opts, "cc_color_max", 4.0),
0.0,
)1234567891011121314151617181920212223242526272829303132from math import cos, sin, pi
def apply_scaling(
alg: str,
current_step: int,
total_steps: int,
bri: float,
con: float,
sat: float,
r: float,
g: float,
b: float,
) -> list:
mod = 1.0
if alg != "Flat":
ratio = float(current_step / total_steps)
rad = ratio * pi / 2
match alg:
case "Cos":
mod = cos(rad)
case "Sin":
mod = sin(rad)
case "1 - Cos":
mod = 1 - cos(rad)
case "1 - Sin":
mod = 1 - sin(rad)
return [bri * mod, con * mod, (sat - 1.0) * mod + 1.0, r * mod, g * mod, b * mod]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from modules.shared import OptionInfo, opts
from modules import scripts
from json import load, dump
from gradio import Slider
import os
section = ("cc", "Vectorscope CC")
def settings():
opts.add_option(
"cc_metadata",
OptionInfo(
True,
"Append Vectorscope CC parameters to generation infotext",
section=section,
category_id="sd",
),
)
opts.add_option(
"cc_no_defaults",
OptionInfo(
True,
'Add the "do_not_save_to_config" flag to all components',
section=section,
category_id="sd",
onchange=reset_ui_config,
)
.info("uncheck this option if you wish to use the built-in Defaults function")
.info("enable again if the extension is not working correctly after an update")
.needs_reload_ui(),
)
for lbl, minVal, maxVal in [
("Brightness", (-5.0, 0.0), (0.0, 5.0)),
("Contrast", (-5.0, 0.0), (0.0, 5.0)),
("Saturation", (0.25, 1.0), (1.0, 1.75)),
("Color", (-4.0, 0.0), (0.0, 4.0)),
]:
opts.add_option(
f"cc_{lbl.lower()}_min",
OptionInfo(
minVal[0],
f"{lbl} - Min",
Slider,
{"step": 0.05, "minimum": minVal[0], "maximum": minVal[1]},
section=section,
category_id="sd",
).needs_reload_ui(),
)
opts.add_option(
f"cc_{lbl.lower()}_max",
OptionInfo(
maxVal[1],
f"{lbl} - Max",
Slider,
{"step": 0.05, "minimum": maxVal[0], "maximum": maxVal[1]},
section=section,
category_id="sd",
).needs_reload_ui(),
)
def reset_ui_config():
extension = "cc.py"
ui_config = os.path.join(scripts.basedir(), "ui-config.json")
with open(ui_config, "r", encoding="utf-8") as json_file:
configs = load(json_file)
cleaned_configs = {
key: value for key, value in configs.items() if extension not in key
}
with open(ui_config, "w", encoding="utf-8") as json_file:
dump(cleaned_configs, json_file)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108from modules import scripts
import gradio as gr
import json
import os
STYLE_FILE = os.path.join(scripts.basedir(), "styles.json")
EMPTY_STYLE = {"styles": {}, "deleted": {}}
class StyleManager:
def __init__(self):
self.STYLE_SHEET: dict = {}
def load_styles(self):
if os.path.isfile(STYLE_FILE):
with open(STYLE_FILE, "r", encoding="utf-8") as json_file:
self.STYLE_SHEET = json.load(json_file)
print("[Vec. CC] Style Sheet Loaded...")
else:
with open(STYLE_FILE, "w+", encoding="utf-8") as json_file:
self.STYLE_SHEET = EMPTY_STYLE
json.dump(self.STYLE_SHEET, json_file)
print("[Vec. CC] Creating Empty Style Sheet...")
return self.list_style()
def list_style(self) -> list[str]:
return list(self.STYLE_SHEET["styles"].keys())
def get_style(self, style_name: str) -> tuple[bool | str | float]:
style: dict = self.STYLE_SHEET["styles"].get(style_name, None)
if not style:
print(f'\n[Error] No Style of name "{style_name}" was found!\n')
return [gr.update()] * 12
return (
style.get("alt", gr.update()),
style.get("brightness", gr.update()),
style.get("contrast", gr.update()),
style.get("saturation", gr.update()),
*style.get("rgb", (gr.update(), gr.update(), gr.update())),
style.get("hr", gr.update()),
style.get("ad", gr.update()),
style.get("rn", gr.update()),
style.get("noise", gr.update()),
style.get("scaling", gr.update()),
)
def save_style(
self,
style_name: str,
latent: bool,
bri: float,
con: float,
sat: float,
r: float,
g: float,
b: float,
hr: bool,
ad: bool,
rn: bool,
noise: str,
scaling: str,
):
if style_name in self.STYLE_SHEET["styles"]:
print(f'\n[Error] Duplicated Style Name: "{style_name}" Detected!')
print("Values were not saved!\n")
return self.list_style()
new_style = {
"alt": latent,
"brightness": bri,
"contrast": con,
"saturation": sat,
"rgb": [r, g, b],
"hr": hr,
"ad": ad,
"rn": rn,
"noise": noise,
"scaling": scaling,
}
self.STYLE_SHEET["styles"].update({style_name: new_style})
with open(STYLE_FILE, "w+") as json_file:
json.dump(self.STYLE_SHEET, json_file)
print(f'\nStyle of Name "{style_name}" Saved!\n')
return self.list_style()
def delete_style(self, style_name: str):
if style_name not in self.STYLE_SHEET["styles"]:
print(f'\n[Error] No Style of name "{style_name}" was found!\n')
return self.list_style()
style: dict = self.STYLE_SHEET["styles"].get(style_name)
self.STYLE_SHEET["deleted"].update({style_name: style})
del self.STYLE_SHEET["styles"][style_name]
with open(STYLE_FILE, "w+") as json_file:
json.dump(self.STYLE_SHEET, json_file)
print(f'\nStyle of name "{style_name}" was deleted!\n')
return self.list_style()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970from modules import scripts
def _grid_reference():
for data in scripts.scripts_data:
if data.script_class.__module__ in (
"scripts.xyz_grid",
"xyz_grid.py",
) and hasattr(data, "module"):
return data.module
raise SystemError("Could not find X/Y/Z Plot...")
def xyz_support(cache: dict):
def apply_field(field):
def _(p, x, xs):
cache.update({field: x})
return _
def choices_bool():
return ["False", "True"]
def choices_method():
return [
"Disabled",
"Straight",
"Straight Abs.",
"Cross",
"Cross Abs.",
"Ones",
"N.Random",
"U.Random",
"Multi-Res",
"Multi-Res Abs.",
]
def choices_scaling():
return ["Flat", "Cos", "Sin", "1 - Cos", "1 - Sin"]
xyz_grid = _grid_reference()
extra_axis_options = [
xyz_grid.AxisOption(
"[Vec.CC] Enable", str, apply_field("Enable"), choices=choices_bool
),
xyz_grid.AxisOption(
"[Vec.CC] Alt.", str, apply_field("Alt"), choices=choices_bool
),
xyz_grid.AxisOption("[Vec.CC] Brightness", float, apply_field("Brightness")),
xyz_grid.AxisOption("[Vec.CC] Contrast", float, apply_field("Contrast")),
xyz_grid.AxisOption("[Vec.CC] Saturation", float, apply_field("Saturation")),
xyz_grid.AxisOption("[Vec.CC] R", float, apply_field("R")),
xyz_grid.AxisOption("[Vec.CC] G", float, apply_field("G")),
xyz_grid.AxisOption("[Vec.CC] B", float, apply_field("B")),
xyz_grid.AxisOption(
"[Adv.CC] Proc. H.Fix", str, apply_field("DoHR"), choices=choices_bool
),
xyz_grid.AxisOption(
"[Adv.CC] Method", str, apply_field("Method"), choices=choices_method
),
xyz_grid.AxisOption(
"[Adv.CC] Scaling", str, apply_field("Scaling"), choices=choices_scaling
),
xyz_grid.AxisOption("[Adv.CC] Randomize", int, apply_field("Random")),
]
xyz_grid.axis_options.extend(extra_axis_options)1112345678910111213141516171819202122232425262728293031{
"prompt": "a photo of a dog",
"negative_prompt": "(low quality, worst quality)",
"sampler_name": "Euler a",
"sampler_index": "euler",
"steps": 24,
"cfg_scale": 6.0,
"batch_size": 1,
"seed": -1,
"width": 512,
"height": 512,
"alwayson_scripts": {
"vectorscope cc": {
"args": [
true,
true,
-2.5,
1.5,
0.85,
0.0,
0.0,
1.0,
false,
false,
false,
"Straight Abs.",
"Flat"
]
}
}
}11123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430from modules.sd_samplers_kdiffusion import KDiffusionSampler
from modules.shared import opts
from modules import scripts
from lib_cc.colorpicker import create_colorpicker
from lib_cc.callback import hook_callbacks
from lib_cc.style import StyleManager
from lib_cc.xyz import xyz_support
from lib_cc import const
from random import seed
import gradio as gr
VERSION = "2.3.2"
style_manager = StyleManager()
style_manager.load_styles()
hook_callbacks()
const.init()
class VectorscopeCC(scripts.Script):
def __init__(self):
self.xyzCache = {}
xyz_support(self.xyzCache)
def title(self):
return "Vectorscope CC"
def show(self, is_img2img):
return scripts.AlwaysVisible
def ui(self, is_img2img):
mode: str = "img" if is_img2img else "txt"
m: str = f'"{mode}"'
with gr.Accordion(
f"Vectorscope CC v{VERSION}", elem_id=f"vec-cc-{mode}", open=False
):
with gr.Row():
enable = gr.Checkbox(label="Enable")
latent = gr.Checkbox(label="Alt. (Stronger Effects)")
with gr.Row():
bri = gr.Slider(
label="Brightness",
value=const.Brightness.default,
minimum=const.Brightness.minimum,
maximum=const.Brightness.maximum,
step=0.05,
)
con = gr.Slider(
label="Contrast",
value=const.Contrast.default,
minimum=const.Contrast.minimum,
maximum=const.Contrast.maximum,
step=0.05,
)
sat = gr.Slider(
label="Saturation",
value=const.Saturation.default,
minimum=const.Saturation.minimum,
maximum=const.Saturation.maximum,
step=0.05,
)
with gr.Row():
with gr.Column():
r = gr.Slider(
label="R",
info="Cyan | Red",
value=const.Color.default,
minimum=const.Color.minimum,
maximum=const.Color.maximum,
step=0.05,
elem_id=f"cc-r-{mode}",
)
g = gr.Slider(
label="G",
info="Magenta | Green",
value=const.Color.default,
minimum=const.Color.minimum,
maximum=const.Color.maximum,
step=0.05,
elem_id=f"cc-g-{mode}",
)
b = gr.Slider(
label="B",
info="Yellow | Blue",
value=const.Color.default,
minimum=const.Color.minimum,
maximum=const.Color.maximum,
step=0.05,
elem_id=f"cc-b-{mode}",
)
for c in (r, g, b):
c.input(
None,
inputs=[r, g, b],
_js=f"(r, g, b) => {{ VectorscopeCC.updateCursor(r, g, b, {m}); }}",
)
create_colorpicker(is_img2img)
with gr.Accordion("Styles", open=False):
with gr.Row(elem_classes="style-rows"):
style_choice = gr.Dropdown(
label="CC Styles", choices=style_manager.list_style(), scale=3
)
apply_btn = gr.Button(
value="Apply Style", elem_id=f"cc-apply-{mode}", scale=2
)
refresh_btn = gr.Button(value="Refresh Style", scale=2)
with gr.Row(elem_classes="style-rows"):
style_name = gr.Textbox(
label="Style Name", lines=1, max_lines=1, scale=3
)
save_btn = gr.Button(
value="Save Style", elem_id=f"cc-save-{mode}", scale=2
)
delete_btn = gr.Button(value="Delete Style", scale=2)
if getattr(opts, "cc_no_defaults", True):
style_choice.do_not_save_to_config = True
[
setattr(comp, "do_not_save_to_config", True)
for comp in (
apply_btn,
refresh_btn,
style_name,
save_btn,
delete_btn,
)
]
with gr.Accordion("Advanced Settings", open=False):
with gr.Row():
doHR = gr.Checkbox(
label="Process Hires. fix",
visible=(not is_img2img),
)
doAD = gr.Checkbox(label="Process Adetailer")
doRN = gr.Checkbox(label="Randomize using Seed")
method = gr.Radio(
choices=(
"Straight",
"Straight Abs.",
"Cross",
"Cross Abs.",
"Ones",
"N.Random",
"U.Random",
"Multi-Res",
"Multi-Res Abs.",
),
label="Noise Settings",
value="Straight Abs.",
)
scaling = gr.Radio(
choices=("Flat", "Cos", "Sin", "1 - Cos", "1 - Sin"),
label="Scaling Settings",
value="Flat",
)
comps: tuple[gr.components.Component] = (
latent,
bri,
con,
sat,
r,
g,
b,
doHR,
doAD,
doRN,
method,
scaling,
)
apply_btn.click(
fn=style_manager.get_style,
inputs=[style_choice],
outputs=[*comps],
).then(
None,
inputs=[r, g, b],
_js=f"(r, g, b) => {{ VectorscopeCC.updateCursor(r, g, b, {m}); }}",
)
save_btn.click(
fn=lambda *args: gr.update(choices=style_manager.save_style(*args)),
inputs=[style_name, *comps],
outputs=[style_choice],
)
delete_btn.click(
fn=lambda name: gr.update(choices=style_manager.delete_style(name)),
inputs=[style_name],
outputs=[style_choice],
)
refresh_btn.click(
fn=lambda: gr.update(choices=style_manager.load_styles()),
outputs=[style_choice],
)
with gr.Row():
reset_btn = gr.Button(value="Reset")
random_btn = gr.Button(value="Randomize")
def on_reset():
return [
gr.update(value=False),
gr.update(value=const.Brightness.default),
gr.update(value=const.Contrast.default),
gr.update(value=const.Saturation.default),
gr.update(value=const.Color.default),
gr.update(value=const.Color.default),
gr.update(value=const.Color.default),
gr.update(value=False),
gr.update(value=False),
gr.update(value=False),
gr.update(value="Straight Abs."),
gr.update(value="Flat"),
]
def on_random():
return [
gr.update(value=const.Brightness.rand()),
gr.update(value=const.Contrast.rand()),
gr.update(value=const.Saturation.rand()),
gr.update(value=const.Color.rand()),
gr.update(value=const.Color.rand()),
gr.update(value=const.Color.rand()),
]
reset_btn.click(
fn=on_reset,
outputs=[*comps],
show_progress="hidden",
).then(
fn=None,
inputs=[r, g, b],
_js=f"(r, g, b) => {{ VectorscopeCC.updateCursor(r, g, b, {m}); }}",
)
random_btn.click(
fn=on_random,
outputs=[bri, con, sat, r, g, b],
show_progress="hidden",
).then(
fn=None,
inputs=[r, g, b],
_js=f"(r, g, b) => {{ VectorscopeCC.updateCursor(r, g, b, {m}); }}",
)
self.paste_field_names = []
self.infotext_fields = [
(enable, "Vec CC Enabled"),
(latent, "Vec CC Alt"),
(bri, "Vec CC Brightness"),
(con, "Vec CC Contrast"),
(sat, "Vec CC Saturation"),
(r, "Vec CC R"),
(g, "Vec CC G"),
(b, "Vec CC B"),
(method, "Vec CC Noise"),
(doHR, "Vec CC Proc HrF"),
(doAD, "Vec CC Proc Ade"),
(doRN, "Vec CC Seed Randomize"),
(scaling, "Vec CC Scaling"),
]
for comp, name in self.infotext_fields:
if getattr(opts, "cc_no_defaults", True):
comp.do_not_save_to_config = True
self.paste_field_names.append(name)
return [enable, *comps]
def process_batch(
self,
p,
enable: bool,
latent: bool,
bri: float,
con: float,
sat: float,
r: float,
g: float,
b: float,
doHR: bool,
doAD: bool,
doRN: bool,
method: str,
scaling: str,
batch_number: int,
prompts: list[str],
seeds: list[int],
subseeds: list[int],
):
enable = self.xyzCache.pop("Enable", str(enable)).lower().strip() == "true"
if not enable:
if len(self.xyzCache) > 0:
print("\n[Vec.CC] x [X/Y/Z Plot] Extension is not Enabled!\n")
self.xyzCache.clear()
setattr(KDiffusionSampler, "vec_cc", {"enable": False})
return p
method = str(self.xyzCache.pop("Method", method))
if method == "Disabled":
setattr(KDiffusionSampler, "vec_cc", {"enable": False})
return p
if "Random" in self.xyzCache.keys():
print("[X/Y/Z Plot] x [Vec.CC] Randomize is Enabled.")
if len(self.xyzCache) > 1:
print("Some parameters will be overridden!")
cc_seed = int(self.xyzCache.pop("Random"))
else:
cc_seed = int(seeds[0]) if doRN else None
latent = self.xyzCache.pop("Alt", str(latent)).lower().strip() == "true"
doHR = self.xyzCache.pop("DoHR", str(doHR)).lower().strip() == "true"
scaling = str(self.xyzCache.pop("Scaling", scaling))
bri = float(self.xyzCache.pop("Brightness", bri))
con = float(self.xyzCache.pop("Contrast", con))
sat = float(self.xyzCache.pop("Saturation", sat))
r = float(self.xyzCache.pop("R", r))
g = float(self.xyzCache.pop("G", g))
b = float(self.xyzCache.pop("B", b))
assert len(self.xyzCache) == 0
if cc_seed:
seed(cc_seed)
bri = const.Brightness.rand()
con = const.Contrast.rand()
sat = const.Saturation.rand()
r = const.Color.rand()
g = const.Color.rand()
b = const.Color.rand()
print(f"\n[Seed: {cc_seed}]")
print(f"> Brightness: {bri}")
print(f"> Contrast: {con}")
print(f"> Saturation: {sat}")
print(f"> R: {r}")
print(f"> G: {g}")
print(f"> B: {b}\n")
if getattr(opts, "cc_metadata", True):
p.extra_generation_params.update(
{
"Vec CC Enabled": enable,
"Vec CC Alt": latent,
"Vec CC Brightness": bri,
"Vec CC Contrast": con,
"Vec CC Saturation": sat,
"Vec CC R": r,
"Vec CC G": g,
"Vec CC B": b,
"Vec CC Noise": method,
"Vec CC Proc HrF": doHR,
"Vec CC Proc Ade": doAD,
"Vec CC Seed Randomize": doRN,
"Vec CC Scaling": scaling,
"Vec CC Version": VERSION,
}
)
steps: int = getattr(p, "firstpass_steps", None) or p.steps
bri /= steps
con /= steps
sat = pow(sat, 1.0 / steps)
r /= steps
g /= steps
b /= steps
mode: str = "x" if latent else "denoised"
setattr(
KDiffusionSampler,
"vec_cc",
{
"enable": True,
"mode": mode,
"bri": bri,
"con": con,
"sat": sat,
"r": r,
"g": g,
"b": b,
"method": method,
"doHR": doHR,
"doAD": doAD,
"scaling": scaling,
"step": steps,
},
)
return p
def before_hr(self, p, enable: bool, *args, **kwargs):
if enable:
steps: int = getattr(p, "hr_second_pass_steps", None) or p.steps
KDiffusionSampler.vec_cc["step"] = steps
return p123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142from modules.processing import process_images, get_fixed_seed
from modules.shared import state
from modules import scripts
from copy import copy
import gradio as gr
import numpy as np
import cv2 as cv
def mergeHDR(imgs: list, path: str, depth: str, fmt: str, gamma: float):
"""https://docs.opencv.org/4.8.0/d2/df0/tutorial_py_hdr.html"""
import datetime
import math
import os
out_dir = os.path.join(os.path.dirname(path), "hdr")
os.makedirs(out_dir, exist_ok=True)
print(f'\nSaving HDR Outputs to "{out_dir}"\n')
imgs_np = [np.asarray(img, dtype=np.uint8) for img in imgs]
merge = cv.createMergeMertens()
hdr = merge.process(imgs_np)
# shift min to 0.0
hdr += math.ceil(0.0 - np.min(hdr) * 1000) / 1000
# print(f"({np.min(hdr)}, {np.max(hdr)}")
target = 65535 if depth == "16bpc" else 255
precision = np.uint16 if depth == "16bpc" else np.uint8
hdr = np.power(hdr, (1 / gamma))
ldr = np.clip(hdr * target, 0, target).astype(precision)
rgb = cv.cvtColor(ldr, cv.COLOR_BGR2RGB)
time = datetime.datetime.now().strftime("%H-%M-%S")
cv.imwrite(os.path.join(out_dir, f"{time}{fmt}"), rgb)
class VectorHDR(scripts.Script):
def title(self):
return "High Dynamic Range"
def show(self, is_img2img):
return True
def ui(self, is_img2img):
with gr.Row():
count = gr.Slider(
label="Brackets",
minimum=3,
maximum=9,
step=2,
value=5,
)
gap = gr.Slider(
label="Gaps",
minimum=0.50,
maximum=2.50,
step=0.25,
value=1.25,
)
with gr.Accordion(
"Merge Options",
elem_id=f'vec-hdr-{"img" if is_img2img else "txt"}',
open=False,
):
auto = gr.Checkbox(label="Automatically Merge", value=True)
with gr.Row():
depth = gr.Radio(["16bpc", "8bpc"], label="Bit Depth", value="16bpc")
fmt = gr.Radio([".tiff", ".png"], label="Image Format", value=".tiff")
gamma = gr.Slider(
label="Gamma",
info="Lower: Darker | Higher: Brighter",
minimum=0.2,
maximum=2.2,
step=0.2,
value=1.2,
)
for comp in (count, gap, auto, depth, fmt, gamma):
comp.do_not_save_to_config = True
return [count, gap, auto, depth, fmt, gamma]
def run(
self, p, count: int, gap: float, auto: bool, depth: str, fmt: str, gamma: float
):
center: int = count // 2
brackets = brightness_brackets(count, gap)
p.seed = get_fixed_seed(p.seed)
p.scripts.script("vectorscope cc").xyzCache.update({"Enable": "False"})
baseline = process_images(p)
pc = copy(p)
imgs = [None] * count
imgs[center] = baseline.images[0]
for it in range(count):
if state.skipped or state.interrupted or state.stopping_generation:
print("HDR Process Skipped...")
return baseline
if it == center:
continue
pc.scripts.script("vectorscope cc").xyzCache.update(
{
"Enable": "True",
"Alt": "True",
"Brightness": brackets[it],
"DoHR": "False",
"Method": "Ones",
"Scaling": "1 - Cos",
}
)
proc = process_images(pc)
imgs[it] = proc.images[0]
if auto:
mergeHDR(imgs, p.outpath_samples, depth, fmt, gamma)
baseline.images = imgs
return baseline
def brightness_brackets(count: int, gap: float) -> list[float]:
half = count // 2
return [gap * (i - half) for i in range(count)]123456789101112131415161718192021222324252627282930313233343536373839#cc-dot-txt, #cc-dot-img {
position: absolute;
width: 24px;
height: 24px;
pointer-events: none;
}
#cc-img-txt, #cc-img-img {
cursor: pointer;
height: 100%;
width: auto;
margin: auto;
}
#vec-cc-txt, #vec-cc-img {
user-select: none;
}
#vec-cc-txt button, #vec-cc-txt label {
border-radius: 0.5em;
}
#vec-cc-img button, #vec-cc-img label {
border-radius: 0.5em;
}
#vec-cc-txt .style-rows {
align-items: end;
gap: 1em;
}
#vec-cc-img .style-rows {
align-items: end;
gap: 1em;
}
#vec-hdr-txt label, #vec-hdr-img label {
border-radius: 0.5em;
}1111111111.gitattributes+1
config.jsonAdded+14
extensions/a.txtAdded+1
extensions/sd-webui-detail-daemon/.gitattributesAdded+2
extensions/sd-webui-detail-daemon/.gitignoreAdded+1
extensions/sd-webui-detail-daemon/LICENSEAdded+21
extensions/sd-webui-detail-daemon/README.mdAdded+82
extensions/sd-webui-detail-daemon/a.txtAdded+1
extensions/sd-webui-detail-daemon/scripts/__pycache__/a.txtAdded+1
extensions/sd-webui-detail-daemon/scripts/__pycache__/detail_daemon.cpython-310.pycAdded
extensions/sd-webui-detail-daemon/scripts/a.txtAdded+1
extensions/sd-webui-detail-daemon/scripts/detail_daemon.pyAdded+313
extensions/sd-webui-detail-daemon/style.cssAdded+20
extensions/sd-webui-vectorscope-cc/.github/FUNDING.ymlAdded+1
extensions/sd-webui-vectorscope-cc/.github/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/.gitignoreAdded+2
extensions/sd-webui-vectorscope-cc/CHANGELOG.mdAdded+145
extensions/sd-webui-vectorscope-cc/LICENSEAdded+21
extensions/sd-webui-vectorscope-cc/README.mdAdded+375
extensions/sd-webui-vectorscope-cc/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/javascript/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/javascript/vec_cc.jsAdded+128
extensions/sd-webui-vectorscope-cc/lib_cc/__init__.pyAdded+4
extensions/sd-webui-vectorscope-cc/lib_cc/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/lib_cc/callback.pyAdded+180
extensions/sd-webui-vectorscope-cc/lib_cc/colorpicker.pyAdded+27
extensions/sd-webui-vectorscope-cc/lib_cc/const.pyAdded+49
extensions/sd-webui-vectorscope-cc/lib_cc/scaling.pyAdded+32
extensions/sd-webui-vectorscope-cc/lib_cc/settings.pyAdded+79
extensions/sd-webui-vectorscope-cc/lib_cc/style.pyAdded+108
extensions/sd-webui-vectorscope-cc/lib_cc/xyz.pyAdded+70
extensions/sd-webui-vectorscope-cc/samples/00.jpgAdded

extensions/sd-webui-vectorscope-cc/samples/01.jpgAdded

extensions/sd-webui-vectorscope-cc/samples/02.jpgAdded

extensions/sd-webui-vectorscope-cc/samples/03.jpgAdded

extensions/sd-webui-vectorscope-cc/samples/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/samples/api_example.jsonAdded+31
extensions/sd-webui-vectorscope-cc/samples/method.jpgAdded

extensions/sd-webui-vectorscope-cc/samples/scaling.jpgAdded

Large File Pointer Details
- SHA256: 4d9a6ff91a7633122644e2ac5c48d21d5b2e706460dd185c7a7c25eaf7ee0ec1
- Pointer size: 132 Bytes
- Size of remote file: 1.17 MB
extensions/sd-webui-vectorscope-cc/scripts/a.txtAdded+1
extensions/sd-webui-vectorscope-cc/scripts/cc.pyAdded+430
extensions/sd-webui-vectorscope-cc/scripts/cc_hdr.pyAdded+142
extensions/sd-webui-vectorscope-cc/scripts/dot.pngAdded

extensions/sd-webui-vectorscope-cc/scripts/vectorscope.pngAdded

extensions/sd-webui-vectorscope-cc/style.cssAdded+39
models/Codeformer/a.txtAdded+1
models/ControlNet/a.txtAdded+1
models/ControlNetPreprocessor/a.txtAdded+1
models/ControlNetPreprocessor/clip_vision/a.txtAdded+1
models/GFPGAN/a.txtAdded+1