File size: 12,612 Bytes
3dabe4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
from modules.sd_samplers_kdiffusion import KDiffusionSampler
from modules import shared, scripts, script_callbacks
import gradio as gr

from scripts.cg_xyz import xyz_support

VERSION = "v1.1.0"

DYNAMIC_RANGE = [3.25, 2.5, 2.5, 2.5]

Default_LUTs = {"C": 0.01, "M": 0.5, "Y": -0.13, "K": 0}


def normalize_tensor(x, r):
    X = x.detach().clone()

    ratio = r / max(abs(float(X.min())), abs(float(X.max())))
    X *= max(ratio, 0.99)

    return X


original_callback = KDiffusionSampler.callback_state


def center_callback(self, d):
    if not self.diffcg_enable or getattr(self.p, "_ad_inner", False):
        return original_callback(self, d)

    X = d["denoised"].detach().clone()
    batchSize = X.size(0)
    channels = len(self.LUTs)

    for b in range(batchSize):
        for c in range(channels):

            if self.diffcg_recenter_strength > 0.0:
                d["denoised"][b][c] += (
                    self.LUTs[c] - X[b][c].mean()
                ) * self.diffcg_recenter_strength

            if self.diffcg_normalize and (d["i"] + 1) > self.diffcg_last_step // 2:
                d["denoised"][b][c] = normalize_tensor(X[b][c], DYNAMIC_RANGE[c])

    return original_callback(self, d)


KDiffusionSampler.callback_state = center_callback


# ["None", "txt2img", "img2img", "Both"]
ac = getattr(shared.opts, "always_center", "None")
an = getattr(shared.opts, "always_normalize", "None")
def_sd = getattr(shared.opts, "default_arch", "1.5")
adv_opt = getattr(shared.opts, "show_center_opt", False)

c_t2i = ac in ("txt2img", "Both")
c_i2i = ac in ("img2img", "Both")
n_t2i = an in ("txt2img", "Both")
n_i2i = an in ("img2img", "Both")


class DiffusionCG(scripts.Script):
    def __init__(self):
        self.xyzCache = {}
        xyz_support(self.xyzCache)

    def title(self):
        return "DiffusionCG"

    def show(self, is_img2img):
        return scripts.AlwaysVisible

    def ui(self, is_img2img):
        with gr.Accordion(f"Diffusion CG {VERSION}", open=False):
            with gr.Row():
                enableG = gr.Checkbox(
                    label="Enable (Global)",
                    value=(
                        ((not is_img2img) and (c_t2i or n_t2i))
                        or (is_img2img and (c_i2i or n_i2i))
                    ),
                )
                sd_ver = gr.Radio(
                    ["1.5", "XL"], value=def_sd, label="Stable Diffusion Version"
                )

            with gr.Row():
                with gr.Group():
                    gr.Markdown('<h3 align="center">Recenter</h3>')

                    if not is_img2img:
                        v = 1.0 if c_t2i else 0.0
                    else:
                        v = 1.0 if c_i2i else 0.0

                    rc_str = gr.Slider(
                        label="Effect Strength",
                        minimum=0.0,
                        maximum=1.0,
                        step=0.2,
                        value=v,
                    )

                with gr.Group():
                    gr.Markdown('<h3 align="center">Normalization</h3>')
                    enableN = gr.Checkbox(
                        label="Activate",
                        value=(((not is_img2img) and n_t2i) or (is_img2img and n_i2i)),
                    )

            with gr.Accordion("Recenter Settings", visible=adv_opt, open=False):
                with gr.Group(visible=(def_sd == "1.5")) as setting15:
                    C = gr.Slider(
                        label="C",
                        minimum=-1.00,
                        maximum=1.00,
                        step=0.01,
                        value=Default_LUTs["C"],
                    )
                    M = gr.Slider(
                        label="M",
                        minimum=-1.00,
                        maximum=1.00,
                        step=0.01,
                        value=Default_LUTs["M"],
                    )
                    Y = gr.Slider(
                        label="Y",
                        minimum=-1.00,
                        maximum=1.00,
                        step=0.01,
                        value=Default_LUTs["Y"],
                    )
                    K = gr.Slider(
                        label="K",
                        minimum=-1.00,
                        maximum=1.00,
                        step=0.01,
                        value=Default_LUTs["K"],
                    )

                with gr.Group(visible=(def_sd == "XL")) as settingXL:
                    L = gr.Slider(
                        label="L", minimum=-1.00, maximum=1.00, step=0.01, value=0.0
                    )
                    a = gr.Slider(
                        label="a", minimum=-1.00, maximum=1.00, step=0.01, value=0.0
                    )
                    b = gr.Slider(
                        label="b", minimum=-1.00, maximum=1.00, step=0.01, value=0.0
                    )

            def on_radio_change(choice):
                if choice == "1.5":
                    return [
                        gr.Group.update(visible=True),
                        gr.Group.update(visible=False),
                    ]
                else:
                    return [
                        gr.Group.update(visible=False),
                        gr.Group.update(visible=True),
                    ]

            sd_ver.change(on_radio_change, sd_ver, [setting15, settingXL])

        self.paste_field_names = [
            (rc_str, "ReCenter Str"),
            (enableN, "Normalization"),
            (sd_ver, "SD_ver"),
        ]
        self.infotext_fields = [
            (rc_str, "ReCenter Str"),
            (enableN, "Normalization"),
            (sd_ver, "SD_ver"),
        ]

        if adv_opt:
            self.paste_field_names += [
                (
                    C,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[0])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    M,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[1])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    Y,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[2])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    K,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[3])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    L,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[0])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
                (
                    a,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[1])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
                (
                    b,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[2])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
            ]
            self.infotext_fields += [
                (
                    C,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[0])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    M,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[1])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    Y,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[2])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    K,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[3])
                        if len(d.get("LUTs", "").split(",")) == 4
                        else gr.update()
                    ),
                ),
                (
                    L,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[0])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
                (
                    a,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[1])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
                (
                    b,
                    lambda d: (
                        float(d["LUTs"].strip("[]").split(",")[2])
                        if len(d.get("LUTs", "").split(",")) == 3
                        else gr.update()
                    ),
                ),
            ]

        for comp in [enableG, sd_ver, rc_str, enableN, C, M, Y, K, L, a, b]:
            comp.do_not_save_to_config = True

        return [enableG, sd_ver, rc_str, enableN, C, M, Y, K, L, a, b]

    def before_hr(self, p, *args):
        KDiffusionSampler.diffcg_normalize = False

    def process(
        self,
        p,
        enableG: bool,
        sd_ver: str,
        rc_str: float,
        enableN: bool,
        C: float,
        M: float,
        Y: float,
        K: float,
        L: float,
        a: float,
        b: float,
    ):

        if "enableG" in self.xyzCache.keys():
            enableG = self.xyzCache["enableG"].lower().strip() == "true"
            del self.xyzCache["enableG"]

        KDiffusionSampler.diffcg_enable = enableG
        if not enableG:
            if len(self.xyzCache.keys()) > 0:
                print("\n[Diff. CG] X [X/Y/Z Plot] Extension is not Enabled!\n")
            self.xyzCache.clear()
            return p

        if "rc_str" in self.xyzCache.keys():
            rc_str = float(self.xyzCache["rc_str"])
        if "enableN" in self.xyzCache.keys():
            enableN = self.xyzCache["enableN"].lower().strip() == "true"

        if adv_opt:
            C = self.xyzCache.get("C", C)
            M = self.xyzCache.get("M", M)
            Y = self.xyzCache.get("Y", Y)
            K = self.xyzCache.get("K", K)
            L = self.xyzCache.get("L", L)
            a = self.xyzCache.get("a", a)
            b = self.xyzCache.get("b", b)

        if sd_ver == "1.5":
            KDiffusionSampler.LUTs = [-K, -M, C, Y]
        else:
            KDiffusionSampler.LUTs = [L, -a, b]

        KDiffusionSampler.diffcg_recenter_strength = rc_str
        KDiffusionSampler.diffcg_normalize = enableN

        if (
            not hasattr(p, "enable_hr")
            and not shared.opts.img2img_fix_steps
            and getattr(p, "denoising_strength", 1.0) < 1.0
        ):
            KDiffusionSampler.diffcg_last_step = int(p.steps * p.denoising_strength) + 1
        else:
            KDiffusionSampler.diffcg_last_step = p.steps

        p.extra_generation_params.update(
            {
                "ReCenter Str": rc_str,
                "Normalization": enableN,
                "SD_ver": sd_ver,
            }
        )

        if adv_opt:
            if def_sd == "1.5":
                p.extra_generation_params["LUTs"] = f"[{C}, {M}, {Y}, {K}]"
            else:
                p.extra_generation_params["LUTs"] = f"[{L}, {a}, {b}]"

        self.xyzCache.clear()


def restore_callback():
    KDiffusionSampler.callback_state = original_callback


script_callbacks.on_script_unloaded(restore_callback)