SemanticPaletteXL / share_btn.py
ironjr's picture
Update share_btn.py
944df8d verified
share_js = """async () => {
async function uploadFile(file) {
const UPLOAD_URL = 'https://huggingface.co/uploads';
const response = await fetch(UPLOAD_URL, {
method: 'POST',
headers: {
'Content-Type': file.type,
'X-Requested-With': 'XMLHttpRequest',
},
body: file, /// <- File inherits from Blob
});
const url = await response.text();
return url;
}
async function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}));
async function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
};
const gradioEl = document.querySelector('body > gradio-app');
const imgEls = gradioEl.querySelectorAll('#output-screen img');
if(!imgEls.length){
return;
};
const urls = await Promise.all([...imgEls].map((imgEl) => {
const origURL = imgEl.src;
const imgId = Date.now() % 200;
const fileName = 'semantic-palette-xl-' + imgId + '.png';
return toDataURL(origURL)
.then(dataUrl => {
return dataURLtoFile(dataUrl, fileName);
})
})).then(fileData => {return Promise.all([...fileData].map((file) => {
return uploadFile(file);
}))});
const htmlImgs = urls.map(url => `<img src='${url}' width='2560' height='1024'>`);
const descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
${htmlImgs.join(`\n`)}
</div>`;
const params = new URLSearchParams({
title: `My creation`,
description: descriptionMd,
});
const paramsStr = params.toString();
window.open(`https://huggingface.co/spaces/ironjr/SemanticPaletteXL/discussions/new?${paramsStr}`, '_blank');
}"""