AIチャット内に画像表示させるやーつのプロンプト隠ぺい版

TanperMonkeyスクリプト

ChatGPTとパープレ以外で使うなら@matchにURLを追加して、 CONTAINER_FILTER_MODE = "off" にすればとりあえず動く

CONTAINER_FILTER_MODE = "strict" のとき
ChatGPTとパープレ(complexity拡張前提)のアンサー欄のテキストだけを置換対象にする条件を ALLOWED_PARENT_SELECTORS に列挙してる
他サイトでも変なところを置換されないよう置換対象を制限した方が安心かも

PROMPT_HIDE_MODE = true のとき、プロンプト全文を置換して不可視にする。falseのとき、🪄マークだけを置換してプロンプトを残す
不可視モードで隠された生成パラメータは、画像をクリックで表示できる

  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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// ==UserScript==
// @name         AIChat Image Replacer + GenImage Trigger (v125.4)
// @match        https://chat.openai.com/*
// @match        https://chatgpt.com/*
// @match        https://www.perplexity.ai/*
// @version      v125.4
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    // === 設定 ===
    const BASE_URL = "https://192.168.1.XXX:8443/";
    const SCAN_INTERVAL_NORMAL = 3000;
    const SCAN_INTERVAL_FAST = 200;
    const FAST_SCAN_WINDOW = 5000;
    const CHANGE_CHECK_INTERVAL = 3000;
    const CONTAINER_FILTER_MODE = "strict"; // "strict"なら限定、"off"なら全体
    const PROMPT_HIDE_MODE = true; // ←ここ true/false で切替

    // サイトごとに要調整
    const ALLOWED_PARENT_SELECTORS = [
        '[data-message-author-role="assistant"]',
        '[data-cplx-component="message-block-answer"]'
    ];

    // ノード結合スキャンが必要なサイトリスト
    const NEEDS_MULTI_NODE_SCAN = [
        "www.perplexity.ai", "perplexity.ai"
        // 追加で必要ならホスト/IPを記載
    ];
    function needsMultiNodeScan() {
        return NEEDS_MULTI_NODE_SCAN.includes(window.location.hostname);
    }

    // === 変数 ===
    let nextScanAt = 0;
    let lastChangeValue = 0;
    let fastModeUntil = 0;

    // === ユーティリティ ===
    const isInputElement = (node) => {
        if (!node || !node.parentNode) return false;
        let current = node.parentNode;
        while (current && current !== document.body) {
            const tag = current.tagName;
            if (["INPUT", "TEXTAREA", "SELECT"].includes(tag)) return true;
            if (current.contentEditable === 'true' ||
                current.getAttribute?.("contenteditable") === "true" ||
                current.classList.contains("ProseMirror") ||
                current.id === "prompt-textarea" ||
                current.getAttribute("data-testid") === "textbox") return true;
            current = current.parentNode;
        }
        return false;
    };
    const isInsideCodeBlock = (node) => {
        let current = node.parentNode;
        while (current && current !== document.body) {
            const tag = current.tagName;
            const cls = current.getAttribute?.("class") || "";
            if (tag === "CODE" || tag === "PRE" ||
                (cls.includes("markdown") && (cls.includes("code") || cls.includes("highlight")))) {
                return true;
            }
            current = current.parentNode;
        }
        return false;
    };
    // 範囲制限
    const isInsideAllowedContainer = (node) => {
        if (CONTAINER_FILTER_MODE === "off") return true;
        let current = node.parentNode;
        while (current && current !== document.body) {
            if (ALLOWED_PARENT_SELECTORS.some(sel => current.matches?.(sel))) return true;
            current = current.parentNode;
        }
        return false;
    };

    // 検索範囲をスクロール付近に限定
    function getVisibleTextNodes(root) {
        const blocks = CONTAINER_FILTER_MODE === "strict"
        ? document.querySelectorAll(ALLOWED_PARENT_SELECTORS.join(','))
        : [root];

        const nodes = [];
        const margin = 2000; // px, スクロール範囲余裕
        const viewportTop = window.scrollY;
        const viewportBottom = viewportTop + window.innerHeight;

        blocks.forEach(block => {
            if (!block.getBoundingClientRect) return;
            const rect = block.getBoundingClientRect();
            const absTop = rect.top + window.scrollY;
            const absBottom = rect.bottom + window.scrollY;
            if (absBottom >= viewportTop - margin && absTop <= viewportBottom + margin) {
                const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, {
                    acceptNode: (node) =>
                    isInputElement(node) || isInsideCodeBlock(node) || !isInsideAllowedContainer(node)
                    ? NodeFilter.FILTER_REJECT
                    : NodeFilter.FILTER_ACCEPT
                });
                let n;
                while ((n = walker.nextNode())) nodes.push(n);
            }
        });
        return nodes;
    }

    // measureDomChange: 最新1件の中身だけ
    function measureDomChange() {
        if (CONTAINER_FILTER_MODE === "strict") {
            const nodes = document.querySelectorAll(ALLOWED_PARENT_SELECTORS.join(','));
            if (!nodes.length) return 0;
            const last = nodes[nodes.length - 1];
            return last.textContent.length;
        } else {
            return 0;
        }
    }

    // --- 以下はほぼ従来どおり ---
    const cameraRegex = /📷《([\w\-/]+\.webp)/giu;
    const genImageRegex = /🪄《prompt:\s*([^|]+?)\s*\|\s*filename:\s*([\w\-/]+\.webp)(?:\s*\|\s*preset:\s*([\w\-.]+))?\s*/giu;

    // 画像生成
    const makeCameraImage = (filename) => {
        const url = BASE_URL + filename;
        const baseName = filename.split("/").pop();
        const isCG = baseName.startsWith("cg_");
        const isWide = baseName.includes("_wide");
        const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);

        const img = document.createElement("img");
        img.src = url;
        img.alt = `⚠️ ${filename}`;
        img.style.verticalAlign = "middle";
        const style = isCG
        ? (isWide ? (isMobile ? "max-width:100%; margin:8px 0;" : "max-width:700px; margin:8px 0;")
           : (isMobile ? "max-width:70%; margin:8px 0;" : "max-width:500px; margin:8px 0;"))
        : (isMobile ? "max-width:150px; margin:4px 0;" : "max-width:200px; margin:4px 0;");
        img.style.cssText += style;

        const wrapper = document.createElement("span");
        wrapper.style.display = "inline-block";
        wrapper.style.marginRight = "8px";
        wrapper.appendChild(img);
        return wrapper;
    };

    // プロンプト不可視モード用:アコーディオン
    const makeWandDetails = (prompt, filename, preset) => {
        let url = `${BASE_URL}generate/${filename}?gen_image=1&prompt=${encodeURIComponent(prompt)}`;
        if (preset) url += `&preset=${encodeURIComponent(preset)}`;

        const details = document.createElement("details");
        details.style.display = "inline-block";
        details.style.verticalAlign = "middle";
        details.style.margin = "0 8px 0 0";

        const summary = document.createElement("summary");
        summary.style.listStyle = "none";
        summary.style.cursor = "pointer";
        summary.style.display = "inline-block";
        summary.style.padding = "0";

        const img = document.createElement("img");
        img.src = url;
        img.alt = `🪄 ${filename}`;
        img.title = "画像生成プロンプトを見る";
        img.style.verticalAlign = "middle";
        img.style.minWidth = "200px";
        img.style.minHeight = "200px";
        img.style.backgroundColor = "#e0f7fa";
        img.style.border = "1px solid #fcfcfc";
        img.style.margin = "8px 0";
        img.style.maxWidth = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "70%" : "500px";

        img.onload = () => {
            img.style.backgroundColor = "transparent";
            img.style.border = "none";
            const aspect = img.naturalWidth / img.naturalHeight;
            const isWide = aspect >= 1.2;
            img.style.maxWidth = isWide ? (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "100%" : "700px")
            : (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "70%" : "500px");
        };
        img.onerror = () => {
            img.style.backgroundColor = "#fee";
            img.style.border = "1px solid red";
            img.alt = "❌ failed to load image";
        };

        summary.appendChild(img);
        details.appendChild(summary);

        const promptText = document.createElement("div");
        promptText.style.fontSize = "0.92em";
        promptText.style.padding = "4px 8px";
        promptText.style.whiteSpace = "pre-wrap";
        promptText.style.border = "1px solid #bbb";
        promptText.style.borderRadius = "8px";
        promptText.style.marginTop = "4px";
        promptText.style.background = "transparent";
        promptText.textContent =
            `prompt: ${prompt}\nfilename: ${filename}` +
            (preset ? `\npreset: ${preset}` : "");
        details.appendChild(promptText);

        return details;
    };

    // 🪄画像
    const makeWandImage = (prompt, filename, preset) => {
        let url = `${BASE_URL}generate/${filename}?gen_image=1&prompt=${encodeURIComponent(prompt)}`;
        if (preset) url += `&preset=${encodeURIComponent(preset)}`;

        const img = document.createElement("img");
        img.src = url;
        img.alt = `🪄 ${filename}`;
        img.title = prompt;
        img.style.verticalAlign = "middle";
        img.style.minWidth = "200px";
        img.style.minHeight = "200px";
        img.style.backgroundColor = "#e0f7fa";
        img.style.border = "1px solid #fcfcfc";
        img.style.margin = "8px 0";
        img.style.maxWidth = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "70%" : "500px";

        img.onload = () => {
            img.style.backgroundColor = "transparent";
            img.style.border = "none";
            const aspect = img.naturalWidth / img.naturalHeight;
            const isWide = aspect >= 1.2;
            img.style.maxWidth = isWide ? (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "100%" : "700px")
            : (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ? "70%" : "500px");
        };
        img.onerror = () => {
            img.style.backgroundColor = "#fee";
            img.style.border = "1px solid red";
            img.alt = "❌ failed to load image";
        };

        const wrapper = document.createElement("span");
        wrapper.style.display = "inline-block";
        wrapper.style.marginRight = "8px";
        wrapper.appendChild(img);
        return wrapper;
    };

    // 📷置換
    const replaceCameraTextNodes = (root) => {
        getVisibleTextNodes(root).forEach(node => {
            const content = node.textContent;
            cameraRegex.lastIndex = 0;
            if (!cameraRegex.test(content)) return;
            cameraRegex.lastIndex = 0;
            const span = document.createElement("span");
            let lastIndex = 0;
            let arr = Array.from(content);
            for (let match; (match = cameraRegex.exec(content)); ) {
                const start = match.index;
                const end = start + match[0].length;
                span.appendChild(document.createTextNode(arr.slice(lastIndex, start).join("")));
                span.appendChild(makeCameraImage(match[1]));
                lastIndex = end;
            }
            span.appendChild(document.createTextNode(arr.slice(lastIndex).join("")));
            node.parentNode.replaceChild(span, node);
        });
    };

    // 🪄単一ノードスキャン
    const replaceGenImageTriggerSingleNode = (root) => {
        getVisibleTextNodes(root).forEach(node => {
            const content = node.textContent;
            genImageRegex.lastIndex = 0;
            const match = genImageRegex.exec(content);
            if (!match) return;

            const span = document.createElement('span');
            if (PROMPT_HIDE_MODE) {
                span.appendChild(makeWandDetails(match[1], match[2], match[3]));
            } else {
                const wandIdx = Array.from(content).indexOf('🪄');
                if (wandIdx >= 0) {
                    const arrWand = Array.from(content);
                    const before = arrWand.slice(0, wandIdx).join("");
                    const after = arrWand.slice(wandIdx + 1).join("");
                    span.appendChild(document.createTextNode(before));
                    span.appendChild(makeWandImage(match[1], match[2], match[3]));
                    span.appendChild(document.createTextNode(after));
                } else {
                    span.appendChild(document.createTextNode(content));
                }
            }
            node.parentNode.replaceChild(span, node);
        });
    };

    // 🪄multi-nodeスキャン(必要なサービスのみ)
    function replaceGenImageTriggerMultiNode(root) {
        if (!needsMultiNodeScan()) return;
        const nodes = getVisibleTextNodes(root);
        if (!nodes.length) return;

        // サロゲートペア安全な配列化
        const nodeArrs = nodes.map(n => Array.from(n.textContent));
        const fullArr = nodeArrs.flat();
        const fullText = fullArr.join('');

        genImageRegex.lastIndex = 0;
        const match = genImageRegex.exec(fullText);
        if (!match) return;

        const strUpToMatch = fullText.slice(0, match.index);
        const arrMatchStart = Array.from(strUpToMatch).length;
        const matchArr = Array.from(match[0]);
        const arrMatchEnd = arrMatchStart + matchArr.length;
        const wandIdxInMatch = matchArr.indexOf('🪄');
        const arrWandIdx = arrMatchStart + wandIdxInMatch;

        let nodeStartIdx = 0;
        const nodeRanges = nodeArrs.map(arr => {
            const range = { start: nodeStartIdx, end: nodeStartIdx + arr.length };
            nodeStartIdx += arr.length;
            return range;
        });

        let replaced = false;
        for (let i = 0; i < nodes.length; i++) {
            const node = nodes[i];
            const range = nodeRanges[i];
            const nodeArr = nodeArrs[i];
            // プロンプト不可視モード
            if (PROMPT_HIDE_MODE && !replaced && arrMatchStart < range.end && arrMatchEnd > range.start) {
                // 置換範囲がこのノードにかかっている
                const localStart = Math.max(0, arrMatchStart - range.start);
                const localEnd = Math.min(nodeArr.length, arrMatchEnd - range.start);
                const before = nodeArr.slice(0, localStart).join('');
                const after = nodeArr.slice(localEnd).join('');
                const span = document.createElement("span");
                span.appendChild(document.createTextNode(before));
                span.appendChild(makeWandDetails(match[1], match[2], match[3]));
                span.appendChild(document.createTextNode(after));
                node.parentNode?.replaceChild(span, node);
                replaced = true;
            } else if (PROMPT_HIDE_MODE && replaced && arrMatchStart < range.end && arrMatchEnd > range.start) {
                // 置換範囲の中に含まれているノードは内容を消す
                node.textContent = '';
            }
            // プロンプト可視モード(従来通り、🪄だけimg化
            else if (!PROMPT_HIDE_MODE && arrWandIdx >= range.start && arrWandIdx < range.end) {
                const localWandIdx = arrWandIdx - range.start;
                const before = nodeArr.slice(0, localWandIdx).join('');
                const after = nodeArr.slice(localWandIdx + 1).join('');
                const span = document.createElement('span');
                span.appendChild(document.createTextNode(before));
                span.appendChild(makeWandImage(match[1], match[2], match[3]));
                span.appendChild(document.createTextNode(after));
                node.parentNode?.replaceChild(span, node);
                break;
            }
        }
    }

    // === 全スキャン
    function fullScan() {
        console.log('scanned');
        replaceCameraTextNodes(document.body);
        replaceGenImageTriggerSingleNode(document.body);
        replaceGenImageTriggerMultiNode(document.body);
    }

    function scanLoop() {
        const now = Date.now();
        const interval = (now < fastModeUntil) ? SCAN_INTERVAL_FAST : SCAN_INTERVAL_NORMAL;
        if (now >= nextScanAt) {
            fullScan();
            nextScanAt = now + interval;
        }
        setTimeout(scanLoop, 50);
    }

    function domChangeMonitorLoop() {
        const now = Date.now();
        const val = measureDomChange();
        if (val !== lastChangeValue) {
            fastModeUntil = now + FAST_SCAN_WINDOW;
            lastChangeValue = val;
        }
        setTimeout(domChangeMonitorLoop, CHANGE_CHECK_INTERVAL);
    }

    function safeInit() {
        setTimeout(() => {
            lastChangeValue = measureDomChange();
            fullScan();
            domChangeMonitorLoop();
            scanLoop();
        }, 2000);
    }

    if (document.readyState === "complete") {
        safeInit();
    } else {
        window.addEventListener("load", safeInit);
        window.addEventListener("pageshow", (e) => {
            if (e.persisted) safeInit();
        });
    }
})();
Edit

Pub: 22 Jun 2025 09:44 UTC

Edit: 06 Jul 2025 12:44 UTC

Views: 40