File size: 9,285 Bytes
194b4ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
function submit_replacer() {
    let arguments_ = Array.from(arguments);
    galleryId = arguments_.pop();
    buttonsId = arguments_.pop();
    extraShowButtonsId = arguments_.pop();
    showSubmitButtons(buttonsId, false);

    let id = randomId();

    requestProgress(id,
        gradioApp().getElementById(galleryId + "_gallery_container"),
        gradioApp().getElementById(galleryId + "_gallery"),
        function () {
            showSubmitButtons(buttonsId, true);
            if (extraShowButtonsId) {
                showSubmitButtons(extraShowButtonsId, true);
            }
        }
    );

    let res = create_submit_args(arguments_);

    res[0] = id;

    console.log(res);
    return res;
}



titles = {
    ...titles,
    "Max resolution on detection": "If one side of the image is smaller than that, it will be resized before detection. It doesn't have effect on inpainting. Reduces vram usage and mask generation time.",
    "Mask Expand": "Mask dilation, px, relative to \"Max resolution on detection\"",
    "Extra mask expand": "Extra mask dilation on hires fix step, px, relative to \"Max resolution on detection\"",
    "Limit avoidance mask canvas resolution on creating": "Limit the canvas created by the button, using \"Max resolution on detection\" option",
    "Limit custom mask canvas resolution on creating": "Limit the canvas created by the button, using \"Max resolution on detection\" option",
    "Hires supersampling": "1.0 is the resolution of original image's crop region, but not smaller then firstpass resolution. More then 1.0 - multiplying on this number each sides. It calculates before limiting resolution, so it still can't be bigger then you set above",
    "Correct aspect ratio": "Preserve original width x height number of pixels, but follow generated mask's aspect ratio. In some cases can hide necessary context",
};


let replacer_gallery = undefined;
onAfterUiUpdate(function () {
    if (!replacer_gallery) {
        replacer_gallery = attachGalleryListeners("replacer");
    }
});


function replacerGetCurrentSourceImg(dummy_component, isAvoid, needLimit, maxResolutionOnDetection) {
    const img = gradioApp().querySelector('#replacer_image div div img');
    let maskId = '';
    if (isAvoid) {
        maskId = 'replacer_avoidance_mask';
    } else {
        maskId = 'replacer_custom_mask';
    }
    const removeButton = gradioApp().getElementById(maskId).querySelector('button[aria-label="Remove Image"]');
    if (removeButton) {
        removeButton.click();
    }
    let resImg = img ? img.src : null;
    return [resImg, isAvoid, needLimit, maxResolutionOnDetection];
}



async function replacer_waitForOpts() {
    for (; ;) {
        if (window.opts && Object.keys(window.opts).length) {
            return window.opts;
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}

var isReplacerZoomAndPanIntegrationApplied = false;

function replacerApplyZoomAndPanIntegration() {
    if (typeof window.applyZoomAndPanIntegration === "function" && !isReplacerZoomAndPanIntegrationApplied) {
        window.applyZoomAndPanIntegration("#replacer_advanced_options", ["#replacer_avoidance_mask", "#replacer_custom_mask"]);

        const maskIds = [...Array(10).keys()].map(i => `#replacer_video_mask_${i + 1}`);
        window.applyZoomAndPanIntegration("#replacer_video_masking_tab", maskIds);

        isReplacerZoomAndPanIntegrationApplied = true;
    }
}

function replacerApplyZoomAndPanIntegration_withMod() {
    if (typeof window.applyZoomAndPanIntegration === "function" && typeof window.applyZoomAndPanIntegration_replacer_mod === "function" && !isReplacerZoomAndPanIntegrationApplied) {
        window.applyZoomAndPanIntegration_replacer_mod("#replacer_advanced_options", ["#replacer_avoidance_mask", "#replacer_custom_mask"]);
        isReplacerZoomAndPanIntegrationApplied = true;
    }
}

onUiUpdate(async () => {
    if (isReplacerZoomAndPanIntegrationApplied) return;
    const opts = await replacer_waitForOpts();

    if ('set_scale_by_when_changing_upscaler' in opts) { // webui 1.9
        replacerApplyZoomAndPanIntegration();
    } else {
        replacerApplyZoomAndPanIntegration_withMod();
    }
});


function replacerRemoveInpaintDiffMaskUpload() {
    const mask = gradioApp().getElementById('replacer_inpaint_diff_mask_view');
    if (!mask) return;
    let imageContainer = mask.getElementsByClassName('image-container')[0];
    if (!imageContainer) return;
    const images = imageContainer.getElementsByTagName('img');

    if (images.length == 0) {
        imageContainer.style.visibility = 'hidden';
    } else {
        imageContainer.style.visibility = 'visible';
    }
}

onUiUpdate(replacerRemoveInpaintDiffMaskUpload);


function replacerRemoveVideoMaskUpload() {
    const maskIds = [...Array(10).keys()].map(i => `replacer_video_mask_${i + 1}`);
    maskIds.forEach((maskId) => {
        const mask = gradioApp().getElementById(maskId);
        if (!mask) return;

        const removeButton = mask.querySelector('button[title="Remove Image"]');
        if (removeButton) {
            removeButton.style.display = "none";
        }

        const imageContainer = mask.getElementsByClassName('image-container')[0];
        if (!imageContainer) return;
        const images = imageContainer.getElementsByTagName('canvas');
        if (images.length == 0) {
            imageContainer.style.visibility = 'hidden';
        } else {
            imageContainer.style.visibility = 'visible';
        }
    });
}

onUiUpdate(replacerRemoveVideoMaskUpload);


onUiLoaded(function () {
    let replacer_generate = gradioApp().getElementById('replacer_generate');
    let replacer_hf_generate = gradioApp().getElementById('replacer_hf_generate');
    let replacer_video_masks_detect_generate = gradioApp().getElementById('replacer_video_masks_detect_generate');
    let replacer_video_gen_generate = gradioApp().getElementById('replacer_video_gen_generate');
    replacer_generate.title = '';
    replacer_hf_generate.title = '';
    replacer_video_masks_detect_generate.title = '';
    replacer_video_gen_generate.title = '';
});




function sendBackToReplacer() {
    let res = Array.from(arguments);

    res[1] = selected_gallery_index();

    return res;
}



function replacer_imageComparisonloadImage() {
    let source_a = gradioApp().getElementById('replacer_image').querySelector('img');
    let source_b = gradioApp().getElementById('replacer_gallery').querySelector('img');

    if (source_a == null || source_b == null) return;

    ImageComparator.img_A.src = source_a.src;
    ImageComparator.img_B.src = source_b.src;
    ImageComparator.reset();
}

function replacer_imageComparisonAddButton() { // https://github.com/Haoming02/sd-webui-image-comparison
    // 0: Off ; 1: Text ; 2: Icon
    let option = 0;
    const replacer_image_comparison = gradioApp().getElementById('replacer_image_comparison');
    if (replacer_image_comparison) {
        option = 2;
        const inputs = gradioApp().getElementById('tab_sd-webui-image-comparison')?.getElementsByTagName('input');
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].disabled = false;
        }
    } else {
        const config = gradioApp().getElementById('setting_comp_send_btn')?.querySelectorAll('label');
        if (!config) return;
        for (let i = 1; i < 3; i++) {
            if (config[i].classList.contains('selected')) {
                option = i;
                break;
            }
        }
    }

    if (option === 0) return;

    const row = gradioApp().getElementById("image_buttons_replacer").querySelector('.form');
    const btn = row.lastElementChild.cloneNode();

    btn.id = "replacer_send_to_comp";
    btn.title = "Send images to comparison tab.";
    if (btn.classList.contains("hidden")) {
        btn.classList.remove("hidden");
    }
    if (option === 1) {
        btn.textContent = "Send to Comparison";
    } else {
        btn.textContent = "🆚";
    }

    btn.addEventListener('click', () => {
        replacer_imageComparisonloadImage();
        ImageComparator.switch_to_comparison();
    });
    row.appendChild(btn);
}

onUiLoaded(replacer_imageComparisonAddButton);


function closeAllVideoMasks() {
    const videoMasks = document.querySelectorAll('.replacer_video_mask');
    videoMasks.forEach((mask, index) => {
        const removeButton = mask.querySelector('button[title="Remove Image"]');
        if (removeButton) {
            removeButton.click();
            const canvases = mask.querySelectorAll('canvas');
            canvases.forEach((canvas) => {
                const ctx = canvas.getContext('2d');
                if (ctx) {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                }
                canvas.width = 0;
                canvas.height = 0;
            });
            const images = mask.querySelectorAll('img');
            images.forEach((img) => {
                img.src = '';
                img.onload = null;
                img.onerror = null;
            });
        }
    });
    return [...arguments];
}


onUiLoaded(function () {
    document.getElementById('replacer_video_open_folder').parentElement.style.display = 'none';
});