ironjr commited on
Commit
b4b56ea
1 Parent(s): 8198f05

Create share_btn.py

Browse files
Files changed (1) hide show
  1. share_btn.py +70 -0
share_btn.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ share_js = """async () => {
2
+ async function uploadFile(file) {
3
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
4
+ const response = await fetch(UPLOAD_URL, {
5
+ method: 'POST',
6
+ headers: {
7
+ 'Content-Type': file.type,
8
+ 'X-Requested-With': 'XMLHttpRequest',
9
+ },
10
+ body: file, /// <- File inherits from Blob
11
+ });
12
+ const url = await response.text();
13
+ return url;
14
+ }
15
+ async function getBase64(file) {
16
+ var reader = new FileReader();
17
+ reader.readAsDataURL(file);
18
+ reader.onload = function () {
19
+ console.log(reader.result);
20
+ };
21
+ reader.onerror = function (error) {
22
+ console.log('Error: ', error);
23
+ };
24
+ }
25
+ const toDataURL = url => fetch(url)
26
+ .then(response => response.blob())
27
+ .then(blob => new Promise((resolve, reject) => {
28
+ const reader = new FileReader()
29
+ reader.onloadend = () => resolve(reader.result)
30
+ reader.onerror = reject
31
+ reader.readAsDataURL(blob)
32
+ }));
33
+ async function dataURLtoFile(dataurl, filename) {
34
+ var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
35
+ bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
36
+ while (n--) {
37
+ u8arr[n] = bstr.charCodeAt(n);
38
+ }
39
+ return new File([u8arr], filename, {type:mime});
40
+ };
41
+
42
+ const gradioEl = document.querySelector('body > gradio-app');
43
+ const imgEls = gradioEl.querySelectorAll('#output-screen img');
44
+ if(!imgEls.length){
45
+ return;
46
+ };
47
+
48
+ const urls = await Promise.all([...imgEls].map((imgEl) => {
49
+ const origURL = imgEl.src;
50
+ const imgId = Date.now() % 200;
51
+ const fileName = 'semantic-palette-xl-' + imgId + '.png';
52
+ return toDataURL(origURL)
53
+ .then(dataUrl => {
54
+ return dataURLtoFile(dataUrl, fileName);
55
+ })
56
+ })).then(fileData => {return Promise.all([...fileData].map((file) => {
57
+ return uploadFile(file);
58
+ }))});
59
+
60
+ const htmlImgs = urls.map(url => `<img src='${url}' width='2560' height='1024'>`);
61
+ const descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
62
+ ${htmlImgs.join(`\n`)}
63
+ </div>`;
64
+ const params = new URLSearchParams({
65
+ title: `My creation`,
66
+ description: descriptionMd,
67
+ });
68
+ const paramsStr = params.toString();
69
+ window.open(`https://huggingface.co/spaces/ironjr/SemanticPaletteXL/discussions/new?${paramsStr}`, '_blank');
70
+ }"""