File size: 5,555 Bytes
1ea2ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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


function isImgUrl(url) {
    const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp)$/i;
    if (url.startsWith('data:image/')) {
        return true;
    }
    if (url.match(imageExtensions)) {
        return true;
    }
    if (url.startsWith('http://') || url.startsWith('https://')) {
        return true;
    }

    return false;
}

function escapeMarkdown(text) {
    /*
    Escape Markdown special characters to HTML-safe equivalents.
    */
    const escapeChars = {
        // ' ': ' ',
        "_": "_",
        "*": "*",
        "[": "[",
        "]": "]",
        "(": "(",
        ")": ")",
        "{": "{",
        "}": "}",
        "#": "#",
        "+": "+",
        "-": "-",
        ".": ".",
        "!": "!",
        "`": "`",
        ">": ">",
        "<": "&#60;",
        "|": "&#124;",
        "$": "&#36;",
        ":": "&#58;",
    };

    text = text.replace(/ {4}/g, "&nbsp;&nbsp;&nbsp;&nbsp;"); // Replace 4 spaces with non-breaking spaces

    let escapedText = "";
    for (let i = 0; i < text.length; i++) {
        const currentChar = text.charAt(i);
        escapedText += escapeChars[currentChar] || currentChar;
    }

    return escapedText;
}

function downloadHistory(gradioUsername, historyname, format=".json") {
    let fileUrl;
    if (gradioUsername === null || gradioUsername.trim() === "") {
        fileUrl = `/file=./history/${historyname}`;
    } else {
        fileUrl = `/file=./history/${gradioUsername}/${historyname}`;
    }
    downloadFile(fileUrl, historyname, format);
}

function downloadFile(fileUrl, filename = "", format = "", retryTimeout = 200, maxAttempts = 10) {

    fileUrl = fileUrl + format;
    filename = filename + format;

    let attempts = 0;

    async function tryDownload() {
        if (attempts >= maxAttempts) {
            console.error('Max attempts reached, download failed.');
            alert('Download failed:' + filename);
            return;
        }
        try {
            const response = await fetch(fileUrl);
            if (!response.ok) {
                attempts++;
                console.error("Error fetching file, retrying...");
                setTimeout(tryDownload, retryTimeout);
            } else {
                response.blob()
                    .then(blob => {
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                    })
                    .catch(error => {
                        console.error('Error downloading file:', error);
                    });
            }
        } catch (error) {
            attempts++;
            setTimeout(tryDownload, retryTimeout);
        }
    }

    tryDownload();
}
    
function statusDisplayMessage(message) {
    statusDisplayBlock = statusDisplay.querySelector("#status-display .md p");
    statusDisplayBlock.innerText = message;
}

function bindFancyBox() {
    Fancybox.bind('[data-fancybox]', {
        Carousel: {
            Panzoom: {
                decelFriction: 0.5
            }
        }
    });
}

function rebootingChuanhu() {
    reloadSpinner = new Spin.Spinner({color:'#06AE56',lines:9}).spin();
    pageInfo = document.createElement('div');
    pageInfo.appendChild(reloadSpinner.el);
    pageInfo.innerHTML += '<h1 style="position: absolute; left: 50%; top: 50%; transform: translateX(-50%); color: lightgray; text-align: center; font-family: sans-serif;">Rebooting...</h1>'
    document.body.innerHTML = '';
    document.body.appendChild(pageInfo);

    var requestPing = function () {
        requestGet("./file=web_assets/manifest.json", {}, function (data) {
            location.reload();
        }, function () {
            setTimeout(requestPing, 500);
        });
    };

    setTimeout(requestPing, 4000);

    return [];
}

/* NOTE: These reload functions are not used in the current version of the code.
 *       From stable-diffusion-webui
 */
function restart_reload() {
    document.body.innerHTML = '<h1 style="font-family:ui-monospace,monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';

    var requestPing = function () {
        requestGet("./internal/ping", {}, function (data) {
            location.reload();
        }, function () {
            setTimeout(requestPing, 500);
        });
    };

    setTimeout(requestPing, 2000);

    return [];
}

function requestGet(url, data, handler, errorHandler) {
    var xhr = new XMLHttpRequest();
    var args = Object.keys(data).map(function (k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
    }).join('&');
    xhr.open("GET", url + "?" + args, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var js = JSON.parse(xhr.responseText);
                    handler(js);
                } catch (error) {
                    console.error(error);
                    errorHandler();
                }
            } else {
                errorHandler();
            }
        }
    };
    var js = JSON.stringify(data);
    xhr.send(js);
}