"use strict" // Opt in to a restricted variant of JavaScript
const HEALTH_PING_INTERVAL = 5 // seconds
const MAX_INIT_IMAGE_DIMENSION = 768
const MIN_GPUS_TO_SHOW_SELECTION = 2
const IMAGE_REGEX = new RegExp('data:image/[A-Za-z]+;base64')
let sessionId = Date.now()
let promptField = document.querySelector('#prompt')
let promptsFromFileSelector = document.querySelector('#prompt_from_file')
let promptsFromFileBtn = document.querySelector('#promptsFromFileBtn')
let negativePromptField = document.querySelector('#negative_prompt')
let numOutputsTotalField = document.querySelector('#num_outputs_total')
let numOutputsParallelField = document.querySelector('#num_outputs_parallel')
let numInferenceStepsField = document.querySelector('#num_inference_steps')
let guidanceScaleSlider = document.querySelector('#guidance_scale_slider')
let guidanceScaleField = document.querySelector('#guidance_scale')
let randomSeedField = document.querySelector("#random_seed")
let seedField = document.querySelector('#seed')
let widthField = document.querySelector('#width')
let heightField = document.querySelector('#height')
let initImageSelector = document.querySelector("#init_image")
let initImagePreview = document.querySelector("#init_image_preview")
let initImageSizeBox = document.querySelector("#init_image_size_box")
let maskImageSelector = document.querySelector("#mask")
let maskImagePreview = document.querySelector("#mask_preview")
let promptStrengthSlider = document.querySelector('#prompt_strength_slider')
let promptStrengthField = document.querySelector('#prompt_strength')
let samplerField = document.querySelector('#sampler')
let samplerSelectionContainer = document.querySelector("#samplerSelection")
let useFaceCorrectionField = document.querySelector("#use_face_correction")
let useUpscalingField = document.querySelector("#use_upscale")
let upscaleModelField = document.querySelector("#upscale_model")
let stableDiffusionModelField = document.querySelector('#stable_diffusion_model')
let vaeModelField = document.querySelector('#vae_model')
let outputFormatField = document.querySelector('#output_format')
let showOnlyFilteredImageField = document.querySelector("#show_only_filtered_image")
let updateBranchLabel = document.querySelector("#updateBranchLabel")
let streamImageProgressField = document.querySelector("#stream_image_progress")
let makeImageBtn = document.querySelector('#makeImage')
let stopImageBtn = document.querySelector('#stopImage')
let imagesContainer = document.querySelector('#current-images')
let initImagePreviewContainer = document.querySelector('#init_image_preview_container')
let initImageClearBtn = document.querySelector('.init_image_clear')
let promptStrengthContainer = document.querySelector('#prompt_strength_container')
let initialText = document.querySelector("#initial-text")
let previewTools = document.querySelector("#preview-tools")
let clearAllPreviewsBtn = document.querySelector("#clear-all-previews")
let maskSetting = document.querySelector('#enable_mask')
let imagePreview = document.querySelector("#preview")
let serverStatusColor = document.querySelector('#server-status-color')
let serverStatusMsg = document.querySelector('#server-status-msg')
document.querySelector('.drawing-board-control-navigation-back').innerHTML = ''
document.querySelector('.drawing-board-control-navigation-forward').innerHTML = ''
let maskResetButton = document.querySelector('.drawing-board-control-navigation-reset')
maskResetButton.innerHTML = 'Clear'
maskResetButton.style.fontWeight = 'normal'
maskResetButton.style.fontSize = '10pt'
let serverState = {'status': 'Offline', 'time': Date.now()}
let bellPending = false
let taskQueue = []
let currentTask = null
function getLocalStorageBoolItem(key, fallback) {
let item = localStorage.getItem(key)
if (item === null) {
return fallback
}
return (item === 'true' ? true : false)
}
function handleBoolSettingChange(key) {
return function(e) {
localStorage.setItem(key, e.target.checked.toString())
}
}
function handleStringSettingChange(key) {
return function(e) {
localStorage.setItem(key, e.target.value.toString())
}
}
function isSoundEnabled() {
return getSetting("sound_toggle")
}
function getSavedDiskPath() {
return getSetting("diskPath")
}
function setStatus(statusType, msg, msgType) {
}
function setServerStatus(msgType, msg) {
switch(msgType) {
case 'online':
serverStatusColor.style.color = 'green'
serverStatusMsg.style.color = 'green'
serverStatusMsg.innerText = 'Stable Diffusion is ' + msg
break
case 'busy':
serverStatusColor.style.color = 'rgb(200, 139, 0)'
serverStatusMsg.style.color = 'rgb(200, 139, 0)'
serverStatusMsg.innerText = 'Stable Diffusion is ' + msg
break
case 'error':
serverStatusColor.style.color = 'red'
serverStatusMsg.style.color = 'red'
serverStatusMsg.innerText = 'Stable Diffusion has stopped'
break
}
}
function isServerAvailable() {
if (typeof serverState !== 'object') {
return false
}
switch (serverState.status) {
case 'LoadingModel':
case 'Rendering':
case 'Online':
return true
default:
return false
}
}
// shiftOrConfirm(e, prompt, fn)
// e : MouseEvent
// prompt : Text to be shown as prompt. Should be a question to which "yes" is a good answer.
// fn : function to be called if the user confirms the dialog or has the shift key pressed
//
// If the user had the shift key pressed while clicking, the function fn will be executed.
// If the setting "confirm_dangerous_actions" in the system settings is disabled, the function
// fn will be executed.
// Otherwise, a confirmation dialog is shown. If the user confirms, the function fn will also
// be executed.
function shiftOrConfirm(e, prompt, fn) {
e.stopPropagation()
if (e.shiftKey || !confirmDangerousActionsField.checked) {
fn(e)
} else {
$.confirm({ theme: 'supervan',
title: prompt,
content: 'Tip: To skip this dialog, use shift-click or disable the setting "Confirm dangerous actions" in the systems setting.',
buttons: {
yes: () => { fn(e) },
cancel: () => {}
}
});
}
}
function logMsg(msg, level, outputMsg) {
if (outputMsg.hasChildNodes()) {
outputMsg.appendChild(document.createElement('br'))
}
if (level === 'error') {
outputMsg.innerHTML += 'Error: ' + msg + ''
} else if (level === 'warn') {
outputMsg.innerHTML += 'Warning: ' + msg + ''
} else {
outputMsg.innerText += msg
}
console.log(level, msg)
}
function logError(msg, res, outputMsg) {
logMsg(msg, 'error', outputMsg)
console.log('request error', res)
setStatus('request', 'error', 'error')
}
function playSound() {
const audio = new Audio('/media/ding.mp3')
audio.volume = 0.2
var promise = audio.play()
if (promise !== undefined) {
promise.then(_ => {}).catch(error => {
console.warn("browser blocked autoplay")
})
}
}
async function healthCheck() {
try {
let res = undefined
if (sessionId) {
res = await fetch('/ping?session_id=' + sessionId)
} else {
res = await fetch('/ping')
}
serverState = await res.json()
if (typeof serverState !== 'object' || typeof serverState.status !== 'string') {
serverState = {'status': 'Offline', 'time': Date.now()}
setServerStatus('error', 'offline')
return
}
// Set status
switch(serverState.status) {
case 'Init':
// Wait for init to complete before updating status.
break
case 'Online':
setServerStatus('online', 'ready')
break
case 'LoadingModel':
setServerStatus('busy', 'loading..')
break
case 'Rendering':
setServerStatus('busy', 'rendering..')
break
default: // Unavailable
setServerStatus('error', serverState.status.toLowerCase())
break
}
if (serverState.devices) {
setDeviceInfo(serverState.devices)
}
serverState.time = Date.now()
} catch (e) {
console.log(e)
serverState = {'status': 'Offline', 'time': Date.now()}
setServerStatus('error', 'offline')
}
}
function showImages(reqBody, res, outputContainer, livePreview) {
let imageItemElements = outputContainer.querySelectorAll('.imgItem')
if(typeof res != 'object') return
res.output.reverse()
res.output.forEach((result, index) => {
const imageData = result?.data || result?.path + '?t=' + Date.now(),
imageSeed = result?.seed,
imagePrompt = reqBody.prompt,
imageInferenceSteps = reqBody.num_inference_steps,
imageGuidanceScale = reqBody.guidance_scale,
imageWidth = reqBody.width,
imageHeight = reqBody.height;
if (!imageData.includes('/')) {
// res contained no data for the image, stop execution
setStatus('request', 'invalid image', 'error')
return
}
let imageItemElem = (index < imageItemElements.length ? imageItemElements[index] : null)
if(!imageItemElem) {
imageItemElem = document.createElement('div')
imageItemElem.className = 'imgItem'
imageItemElem.innerHTML = `
`
outputContainer.appendChild(imageItemElem)
}
const imageElem = imageItemElem.querySelector('img')
imageElem.src = imageData
imageElem.width = parseInt(imageWidth)
imageElem.height = parseInt(imageHeight)
imageElem.setAttribute('data-prompt', imagePrompt)
imageElem.setAttribute('data-steps', imageInferenceSteps)
imageElem.setAttribute('data-guidance', imageGuidanceScale)
const imageInfo = imageItemElem.querySelector('.imgItemInfo')
imageInfo.style.visibility = (livePreview ? 'hidden' : 'visible')
if ('seed' in result && !imageElem.hasAttribute('data-seed')) {
const req = Object.assign({}, reqBody, {
seed: result?.seed || reqBody.seed
})
imageElem.setAttribute('data-seed', req.seed)
const imageSeedLabel = imageItemElem.querySelector('.imgSeedLabel')
imageSeedLabel.innerText = 'Seed: ' + req.seed
let buttons = [
{ text: 'Use as Input', on_click: onUseAsInputClick },
{ text: 'Download', on_click: onDownloadImageClick },
{ text: 'Make Similar Images', on_click: onMakeSimilarClick },
{ text: 'Draw another 25 steps', on_click: onContinueDrawingClick },
{ text: 'Upscale', on_click: onUpscaleClick, filter: (req, img) => !req.use_upscale },
{ text: 'Fix Faces', on_click: onFixFacesClick, filter: (req, img) => !req.use_face_correction }
]
// include the plugins
buttons = buttons.concat(PLUGINS['IMAGE_INFO_BUTTONS'])
const imgItemInfo = imageItemElem.querySelector('.imgItemInfo')
const img = imageItemElem.querySelector('img')
const createButton = function(btnInfo) {
const newButton = document.createElement('button')
newButton.classList.add('tasksBtns')
newButton.innerText = btnInfo.text
newButton.addEventListener('click', function() {
btnInfo.on_click(req, img)
})
imgItemInfo.appendChild(newButton)
}
buttons.forEach(btn => {
if (btn.filter && btn.filter(req, img) === false) {
return
}
createButton(btn)
})
}
})
}
function onUseAsInputClick(req, img) {
const imgData = img.src
initImageSelector.value = null
initImagePreview.src = imgData
initImagePreviewContainer.style.display = 'block'
inpaintingEditorContainer.style.display = 'none'
promptStrengthContainer.style.display = 'table-row'
maskSetting.checked = false
samplerSelectionContainer.style.display = 'none'
}
function onDownloadImageClick(req, img) {
const imgData = img.src
const imageSeed = img.getAttribute('data-seed')
const imagePrompt = img.getAttribute('data-prompt')
const imageInferenceSteps = img.getAttribute('data-steps')
const imageGuidanceScale = img.getAttribute('data-guidance')
const imgDownload = document.createElement('a')
imgDownload.download = createFileName(imagePrompt, imageSeed, imageInferenceSteps, imageGuidanceScale, req['output_format'])
imgDownload.href = imgData
imgDownload.click()
}
function modifyCurrentRequest(...reqDiff) {
const newTaskRequest = getCurrentUserRequest()
newTaskRequest.reqBody = Object.assign(newTaskRequest.reqBody, ...reqDiff, {
use_cpu: useCPUField.checked
})
newTaskRequest.seed = newTaskRequest.reqBody.seed
return newTaskRequest
}
function onMakeSimilarClick(req, img) {
const newTaskRequest = modifyCurrentRequest(req, {
num_outputs: 1,
num_inference_steps: 50,
guidance_scale: 7.5,
prompt_strength: 0.7,
init_image: img.src,
seed: Math.floor(Math.random() * 10000000)
})
newTaskRequest.numOutputsTotal = 5
newTaskRequest.batchCount = 5
delete newTaskRequest.reqBody.mask
createTask(newTaskRequest)
}
function enqueueImageVariationTask(req, img, reqDiff) {
const imageSeed = img.getAttribute('data-seed')
const newTaskRequest = modifyCurrentRequest(req, reqDiff, {
num_outputs: 1, // this can be user-configurable in the future
seed: imageSeed
})
newTaskRequest.numOutputsTotal = 1 // this can be user-configurable in the future
newTaskRequest.batchCount = 1
createTask(newTaskRequest)
}
function onUpscaleClick(req, img) {
enqueueImageVariationTask(req, img, {
use_upscale: upscaleModelField.value
})
}
function onFixFacesClick(req, img) {
enqueueImageVariationTask(req, img, {
use_face_correction: 'GFPGANv1.3'
})
}
function onContinueDrawingClick(req, img) {
enqueueImageVariationTask(req, img, {
num_inference_steps: parseInt(req.num_inference_steps) + 25
})
}
// makes a single image. don't call this directly, use makeImage() instead
async function doMakeImage(task) {
if (task.stopped) {
return
}
const RETRY_DELAY_IF_BUFFER_IS_EMPTY = 1000 // ms
const RETRY_DELAY_IF_SERVER_IS_BUSY = 30 * 1000 // ms, status_code 503, already a task running
const TASK_START_DELAY_ON_SERVER = 1500 // ms
const SERVER_STATE_VALIDITY_DURATION = 90 * 1000 // ms
const reqBody = task.reqBody
const batchCount = task.batchCount
const outputContainer = document.createElement('div')
outputContainer.className = 'img-batch'
task.outputContainer.insertBefore(outputContainer, task.outputContainer.firstChild)
const outputMsg = task['outputMsg']
const previewPrompt = task['previewPrompt']
const progressBar = task['progressBar']
const progressBarInner = progressBar.querySelector("div")
let res = undefined
try {
let renderRequest = undefined
do {
res = await fetch('/render', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(reqBody)
})
renderRequest = await res.json()
// status_code 503, already a task running.
} while (res.status === 503 && await asyncDelay(RETRY_DELAY_IF_SERVER_IS_BUSY))
if (typeof renderRequest?.stream !== 'string') {
console.log('Endpoint response: ', renderRequest)
throw new Error(renderRequest?.detail || 'Endpoint response does not contains a response stream url.')
}
task['taskStatusLabel'].innerText = "Waiting"
task['taskStatusLabel'].classList.add('waitingTaskLabel')
task['taskStatusLabel'].classList.remove('activeTaskLabel')
do { // Wait for server status to update.
await asyncDelay(250)
if (!isServerAvailable()) {
throw new Error('Connexion with server lost.')
}
} while (Date.now() < (serverState.time + SERVER_STATE_VALIDITY_DURATION) && serverState.task !== renderRequest.task)
switch(serverState.session) {
case 'pending':
case 'running':
case 'buffer':
// Normal expected messages.
break
case 'completed':
console.warn('Server %o render request %o completed unexpectedly', serverState, renderRequest)
break // Continue anyway to try to read cached result.
case 'error':
console.error('Server %o render request %o has failed', serverState, renderRequest)
break // Still valid, Update UI with error message
case 'stopped':
console.log('Server %o render request %o was stopped', serverState, renderRequest)
return false
default:
throw new Error('Unexpected server task state: ' + serverState.session || 'Undefined')
}
while (serverState.task === renderRequest.task && serverState.session === 'pending') {
// Wait for task to start on server.
await asyncDelay(TASK_START_DELAY_ON_SERVER)
}
// Task started!
res = await fetch(renderRequest.stream, {
headers: {
'Content-Type': 'application/json'
},
})
task['taskStatusLabel'].innerText = "Processing"
task['taskStatusLabel'].classList.add('activeTaskLabel')
task['taskStatusLabel'].classList.remove('waitingTaskLabel')
let stepUpdate = undefined
let reader = res.body.getReader()
let textDecoder = new TextDecoder()
let finalJSON = ''
let readComplete = false
while (!readComplete || finalJSON.length > 0) {
let t = Date.now()
let jsonStr = ''
if (!readComplete) {
const {value, done} = await reader.read()
if (done) {
readComplete = true
}
if (value) {
jsonStr = textDecoder.decode(value)
}
}
stepUpdate = undefined
try {
// hack for a middleman buffering all the streaming updates, and unleashing them on the poor browser in one shot.
// this results in having to parse JSON like {"step": 1}{"step": 2}{"step": 3}{"ste...
// which is obviously invalid and can happen at any point while rendering.
// So we need to extract only the next {} section
if (finalJSON.length > 0) {
// Append new data when required
if (jsonStr.length > 0) {
jsonStr = finalJSON + jsonStr
} else {
jsonStr = finalJSON
}
finalJSON = ''
}
// Find next delimiter
let lastChunkIdx = jsonStr.indexOf('}{')
if (lastChunkIdx !== -1) {
finalJSON = jsonStr.substring(0, lastChunkIdx + 1)
jsonStr = jsonStr.substring(lastChunkIdx + 1)
} else {
finalJSON = jsonStr
jsonStr = ''
}
// Try to parse
stepUpdate = (finalJSON.length > 0 ? JSON.parse(finalJSON) : undefined)
finalJSON = jsonStr
} catch (e) {
if (e instanceof SyntaxError && !readComplete) {
finalJSON += jsonStr
} else {
throw e
}
}
if (typeof stepUpdate === 'object' && 'step' in stepUpdate) {
let batchSize = stepUpdate.total_steps
let overallStepCount = stepUpdate.step + task.batchesDone * batchSize
let totalSteps = batchCount * batchSize
let percent = 100 * (overallStepCount / totalSteps)
percent = (percent > 100 ? 100 : percent)
percent = percent.toFixed(0)
let timeTaken = stepUpdate.step_time // sec
let stepsRemaining = totalSteps - overallStepCount
stepsRemaining = (stepsRemaining < 0 ? 0 : stepsRemaining)
let timeRemaining = (timeTaken === -1 ? '' : stepsRemaining * timeTaken * 1000) // ms
outputMsg.innerHTML = `Batch ${task.batchesDone+1} of ${batchCount}`
outputMsg.innerHTML += `. Generating image(s): ${percent}%`
timeRemaining = (timeTaken !== -1 ? millisecondsToStr(timeRemaining) : '')
outputMsg.innerHTML += `. Time remaining (approx): ${timeRemaining}`
outputMsg.style.display = 'block'
progressBarInner.style.width = `${percent}%`
if (percent == 100) {
task.progressBar.style.height = "0px"
task.progressBar.style.border = "0px solid var(--background-color3)"
task.progressBar.classList.remove("active")
}
if (stepUpdate.output !== undefined) {
showImages(reqBody, stepUpdate, outputContainer, true)
}
}
if (stepUpdate?.status) {
break
}
if (readComplete && finalJSON.length <= 0) {
if (res.status === 200) {
await asyncDelay(RETRY_DELAY_IF_BUFFER_IS_EMPTY)
res = await fetch(renderRequest.stream, {
headers: {
'Content-Type': 'application/json'
},
})
reader = res.body.getReader()
readComplete = false
} else {
console.log('Stream stopped: ', res)
}
}
}
if (typeof stepUpdate === 'object' && stepUpdate.status !== 'succeeded') {
let msg = ''
if ('detail' in stepUpdate && typeof stepUpdate.detail === 'string' && stepUpdate.detail.length > 0) {
msg = stepUpdate.detail
if (msg.toLowerCase().includes('out of memory')) {
msg += `
Suggestions:
1. If you have set an initial image, please try reducing its dimension to ${MAX_INIT_IMAGE_DIMENSION}x${MAX_INIT_IMAGE_DIMENSION} or smaller.
2. Try disabling the 'Turbo mode' under 'Advanced Settings'.
3. Try generating a smaller image. `
}
} else {
msg = `Unexpected Read Error: