sd_backup / PNG_info_web.js
daasd's picture
Update PNG_info_web.js
90a1b0b
raw
history blame
20.1 kB
//crc32与extrachunks与decode
/* crc32.js (C) 2014-2015 SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
var CRC32;
(function (factory) {
if(typeof DO_NOT_EXPORT_CRC === 'undefined') {
if('object' === typeof exports) {
factory(exports);
} else if ('function' === typeof define && define.amd) {
define(function () {
var module = {};
factory(module);
return module;
});
} else {
factory(CRC32 = {});
}
} else {
factory(CRC32 = {});
}
}(function(CRC32) {
CRC32.version = '0.3.0';
/* see perf/crc32table.js */
function signed_crc_table() {
var c = 0, table = new Array(256);
for(var n =0; n != 256; ++n){
c = n;
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
table[n] = c;
}
return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
}
var table = signed_crc_table();
/* charCodeAt is the best approach for binary strings */
var use_buffer = typeof Buffer !== 'undefined';
function crc32_bstr(bstr) {
if(bstr.length > 32768) if(use_buffer) return crc32_buf_8(new Buffer(bstr));
var crc = -1, L = bstr.length - 1;
for(var i = 0; i < L;) {
crc = table[(crc ^ bstr.charCodeAt(i++)) & 0xFF] ^ (crc >>> 8);
crc = table[(crc ^ bstr.charCodeAt(i++)) & 0xFF] ^ (crc >>> 8);
}
if(i === L) crc = (crc >>> 8) ^ table[(crc ^ bstr.charCodeAt(i)) & 0xFF];
return crc ^ -1;
}
function crc32_buf(buf) {
if(buf.length > 10000) return crc32_buf_8(buf);
for(var crc = -1, i = 0, L=buf.length-3; i < L;) {
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
}
while(i < L+3) crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
return crc ^ -1;
}
function crc32_buf_8(buf) {
for(var crc = -1, i = 0, L=buf.length-7; i < L;) {
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
}
while(i < L+7) crc = (crc >>> 8) ^ table[(crc^buf[i++])&0xFF];
return crc ^ -1;
}
/* much much faster to intertwine utf8 and crc */
function crc32_str(str) {
for(var crc = -1, i = 0, L=str.length, c, d; i < L;) {
c = str.charCodeAt(i++);
if(c < 0x80) {
crc = (crc >>> 8) ^ table[(crc ^ c) & 0xFF];
} else if(c < 0x800) {
crc = (crc >>> 8) ^ table[(crc ^ (192|((c>>6)&31))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|(c&63))) & 0xFF];
} else if(c >= 0xD800 && c < 0xE000) {
c = (c&1023)+64; d = str.charCodeAt(i++) & 1023;
crc = (crc >>> 8) ^ table[(crc ^ (240|((c>>8)&7))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|((c>>2)&63))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|((d>>6)&15)|(c&3))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|(d&63))) & 0xFF];
} else {
crc = (crc >>> 8) ^ table[(crc ^ (224|((c>>12)&15))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|((c>>6)&63))) & 0xFF];
crc = (crc >>> 8) ^ table[(crc ^ (128|(c&63))) & 0xFF];
}
}
return crc ^ -1;
}
CRC32.table = table;
CRC32.bstr = crc32_bstr;
CRC32.buf = crc32_buf;
CRC32.str = crc32_str;
}));
/* crc32.js (C) 2014-2015 SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
// import crc32 from './crc32.js'
// Used for fast-ish conversion between uint8s and uint32s/int32s.
// Also required in order to remain agnostic for both Node Buffers and
// Uint8Arrays.
var uint8 = new Uint8Array(4)
var int32 = new Int32Array(uint8.buffer)
var uint32 = new Uint32Array(uint8.buffer)
function extractChunks (data) {
if (data[0] !== 0x89) throw new Error('Invalid .png file header')
if (data[1] !== 0x50) throw new Error('Invalid .png file header')
if (data[2] !== 0x4E) throw new Error('Invalid .png file header')
if (data[3] !== 0x47) throw new Error('Invalid .png file header')
if (data[4] !== 0x0D) throw new Error('Invalid .png file header: possibly caused by DOS-Unix line ending conversion?')
if (data[5] !== 0x0A) throw new Error('Invalid .png file header: possibly caused by DOS-Unix line ending conversion?')
if (data[6] !== 0x1A) throw new Error('Invalid .png file header')
if (data[7] !== 0x0A) throw new Error('Invalid .png file header: possibly caused by DOS-Unix line ending conversion?')
var ended = false
var chunks = []
var idx = 8
while (idx < data.length) {
// Read the length of the current chunk,
// which is stored as a Uint32.
uint8[3] = data[idx++]
uint8[2] = data[idx++]
uint8[1] = data[idx++]
uint8[0] = data[idx++]
// Chunk includes name/type for CRC check (see below).
var length = uint32[0] + 4
var chunk = new Uint8Array(length)
chunk[0] = data[idx++]
chunk[1] = data[idx++]
chunk[2] = data[idx++]
chunk[3] = data[idx++]
// Get the name in ASCII for identification.
var name = (
String.fromCharCode(chunk[0]) +
String.fromCharCode(chunk[1]) +
String.fromCharCode(chunk[2]) +
String.fromCharCode(chunk[3])
)
// The IHDR header MUST come first.
if (!chunks.length && name !== 'IHDR') {
throw new Error('IHDR header missing')
}
// The IEND header marks the end of the file,
// so on discovering it break out of the loop.
if (name === 'IEND') {
ended = true
chunks.push({
name: name,
data: new Uint8Array(0)
})
break
}
// Read the contents of the chunk out of the main buffer.
for (var i = 4; i < length; i++) {
chunk[i] = data[idx++]
}
// Read out the CRC value for comparison.
// It's stored as an Int32.
uint8[3] = data[idx++]
uint8[2] = data[idx++]
uint8[1] = data[idx++]
uint8[0] = data[idx++]
var crcActual = int32[0]
var crcExpect = CRC32.buf(chunk)
if (crcExpect !== crcActual) {
throw new Error(
'CRC values for ' + name + ' header do not match, PNG file is likely corrupted'
)
}
// The chunk data is now copied to remove the 4 preceding
// bytes used for the chunk name/type.
var chunkData = new Uint8Array(chunk.buffer.slice(4))
chunks.push({
name: name,
data: chunkData
})
}
if (!ended) {
throw new Error('.png file ended prematurely: no IEND header was found')
}
return chunks
}
//decode
function decode (data) {
if (data.data && data.name) {
data = data.data
}
var naming = true
var text = ''
var name = ''
for (var i = 0; i < data.length; i++) {
var code = data[i]
if (naming) {
if (code) {
name += String.fromCharCode(code)
} else {
naming = false
}
} else {
if (code) {
text += String.fromCharCode(code)
} else {
throw new Error('Invalid NULL character found. 0x00 character is not permitted in tEXt content')
}
}
}
return {
keyword: name,
text: text
}
}
const readNovelAITag = async (file) => {
const buf = await file.arrayBuffer();
let chunks = [];
try {
chunks = extractChunks(new Uint8Array(buf));
console.log(chunks)
} catch (err) {
return chunks;
}
let textChunks = chunks
.filter(function (chunk) {
return chunk.name === "tEXt" || chunk.name === "iTXt";
})
console.log(textChunks)
textChunks=textChunks.map(function (chunk) {
if (chunk.name === "iTXt") {
let data = chunk.data.filter((x) => x != 0x0);
let txt = new TextDecoder().decode(data);
return {
keyword: "信息",
text: txt.slice(10),
};
}
return decode(chunk.data);
});
console.log(textChunks);
return textChunks;
}
function convertImageToBlob(fileUrl) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', fileUrl, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
const blob = new Blob([xhr.response], { type: 'image/png' });
resolve(blob);
} else {
reject(new Error('Failed to load image'));
}
};
xhr.onerror = function() {
reject(new Error('Failed to load image'));
};
xhr.send();
});
}
async function convertDomImageToBlob(imageElement) {
const imageUrl = imageElement.src;
const blob = await convertImageToBlob(imageUrl);
const file = new File([blob], 'filename.png', { type: blob.type });
return file;
}
let delayPng_info=function(){
return new Promise(resolve=>{
const shadowRoot = document.querySelector('gradio-app')
// console.log(shadowRoot)
const observer = new MutationObserver((mutations) => {
console.log(4)
mutations.forEach((mutation) => {
// 如果 id 为 pnginfo_image 的子元素被添加到 gradio-app 元素中
if (mutation.addedNodes.length && mutation.addedNodes[0].id === 'pnginfo_image') {
console.log(mutation.addedNodes[0])
// 取消监听
observer.disconnect();
// 获取 id 为 pnginfo_image 的元素并进行操作
resolve(mutation.addedNodes[0])
}
});
});
observer.observe(shadowRoot, { childList: true ,subtree:true});
})
}
async function png_info_edit() {
console.log(123)
const elem = document.querySelector('gradio-app');
const shadowRoot = elem
const png_info = await delayPng_info()
png_info.addEventListener('change', (e) => {
// 获取用户选择的文件
// const file = png_info.files[0];
setTimeout(async () => {
const png_info_img = await png_info.querySelector('img')
let png_info_img_convert = await convertDomImageToBlob(png_info_img)
console.log(png_info_img_convert)
let res=await readNovelAITag(png_info_img_convert)
console.log('res',res)
shadowRoot.querySelector('#component-677').innerText=res.length?res[0].text:'这不是一张stablediffusion图片'
//js对象形式转化
const result = {};
// const match = inputString.match(/(?<=prompt:)(.*)(?=Negative prompt:)/s)[0].trim();]
console.log(res[0].text)
result.prompt = res[0].text.match(/(.*)(?=Negative prompt:)/s)[0].trim();
result.negativePrompt = res[0].text.match(/(?<=Negative prompt:)(.*)(?=Steps:)/s)[0].trim();
let resArr=res[0].text.split(result.negativePrompt)[1].trim().split(',')
console.log(resArr)
resArr.forEach(e=>{result[e.split(':')[0].replaceAll(' ','')]=
e.split(':')[1].trim()
})
console.log(result)
console.log('result',result)
const inputEvent = new Event('input');
const changeEvent = new Event('change');
const click = new Event('click');
shadowRoot.querySelector('#txt2img_tab').onclick=()=>{
shadowRoot.querySelector('[class="tab-nav scroll-hide svelte-1g805jl"]').children[0].click()
shadowRoot.querySelectorAll('#setting_CLIP_stop_at_last_layers input')[0].value=Number(result.Clipskip)
shadowRoot.querySelectorAll('#setting_CLIP_stop_at_last_layers input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#setting_CLIP_stop_at_last_layers input')[1].value=Number(result.Clipskip)
shadowRoot.querySelectorAll('#setting_CLIP_stop_at_last_layers input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelector('#txt2img_prompt textarea').value=result.prompt
shadowRoot.querySelector('#txt2img_prompt textarea').dispatchEvent(inputEvent);
shadowRoot.querySelector('#txt2img_neg_prompt textarea').value=result.negativePrompt
shadowRoot.querySelector('#txt2img_neg_prompt textarea').dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_steps input')[0].value=Number(result.Steps)
shadowRoot.querySelectorAll('#txt2img_steps input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_steps input')[1].value=Number(result.Steps)
shadowRoot.querySelectorAll('#txt2img_steps input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelector(`[value="${result.Sampler}"]`).checked = true;
shadowRoot.querySelector(`[value="${result.Sampler}"]`).dispatchEvent(changeEvent);
shadowRoot.querySelectorAll('#txt2img_width input')[0].value=Number(result.Size.split('x')[0])
shadowRoot.querySelectorAll('#txt2img_width input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_width input')[1].value=Number(result.Size.split('x')[0])
shadowRoot.querySelectorAll('#txt2img_width input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_height input')[0].value=Number(result.Size.split('x')[1])
shadowRoot.querySelectorAll('#txt2img_height input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_height input')[1].value=Number(result.Size.split('x')[1])
shadowRoot.querySelectorAll('#txt2img_height input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelector('#txt2img_seed input').value=Number(result.Seed)
shadowRoot.querySelector('#txt2img_seed input').dispatchEvent(inputEvent);
//高清修复
shadowRoot.querySelector('#txt2img_enable_hr input').checked = !!result.Hiresupscaler
shadowRoot.querySelector('#txt2img_enable_hr input').dispatchEvent(changeEvent)
if(!!result.Hiresupscaler){
const inputElement = document.querySelector("#txt2img_hr_upscaler > label > div > div.wrap-inner.svelte-a6vu2r > div > input");
const mousevent = new MouseEvent('mousedown', {
view: window,
bubbles: true,
cancelable: true
});
inputElement.dispatchEvent(mousevent);
setTimeout(() => {
console.log(`[data-value="${result.Hiresupscaler}"]`)
shadowRoot.querySelector(`[data-value="${result.Hiresupscaler}"]`).click()
}, 3000);
}
// shadowRoot.querySelector('#txt2img_hr_upscaler .single-select').innerText = result.Hiresupscaler||'None'
// shadowRoot.querySelector('#txt2img_hr_upscaler .single-select').dispatchEvent(changeEvent)
shadowRoot.querySelectorAll('#txt2img_hires_steps input')[0].value=Number(result.Hiressteps)||0
shadowRoot.querySelectorAll('#txt2img_hires_steps input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_hires_steps input')[1].value=Number(result.Hiressteps)||0
shadowRoot.querySelectorAll('#txt2img_hires_steps input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_denoising_strength input')[0].value=Number(result.Denoisingstrength)||0
shadowRoot.querySelectorAll('#txt2img_denoising_strength input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_denoising_strength input')[1].value=Number(result.Denoisingstrength)||0
shadowRoot.querySelectorAll('#txt2img_denoising_strength input')[1].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_hr_scale input')[0].value=Number(result.Hiresupscale)||1
shadowRoot.querySelectorAll('#txt2img_hr_scale input')[0].dispatchEvent(inputEvent);
shadowRoot.querySelectorAll('#txt2img_hr_scale input')[1].value=Number(result.Hiresupscale)||1
shadowRoot.querySelectorAll('#txt2img_hr_scale input')[1].dispatchEvent(inputEvent);
}
},100)
});
}
document.addEventListener('DOMContentLoaded', () => {
png_info_edit()
});