File size: 15,830 Bytes
e8d6409 1589e5a ef03766 e8d6409 ef03766 e8d6409 ef03766 e8d6409 bdabd27 0dfc33a e8d6409 c0bd384 6b1cf92 847ea5c 558d0d7 c0bd384 a303e78 79df262 a303e78 e8d6409 b71f89a 558d0d7 e8d6409 558d0d7 e8d6409 ef03766 e8d6409 9560811 e8d6409 558d0d7 bdabd27 558d0d7 e8d6409 79df262 e8d6409 ef03766 42335bd 79df262 e8d6409 46341af 122e32e ba26a7d 73f2651 a303e78 ba26a7d b71f89a 3005416 ba26a7d 79df262 0f49c61 79df262 0f49c61 79df262 558d0d7 ba26a7d e8d6409 a303e78 ba26a7d a303e78 ba26a7d a303e78 ba26a7d 39354ef ed6c657 ba26a7d bdabd27 ba26a7d 73f2651 44d0a2b 1c8a9b2 e8d6409 ed6c657 e8d6409 39354ef e8d6409 6b1cf92 9acf02f ba26a7d e8d6409 ed6c657 1021108 ed6c657 3005416 558d0d7 6934440 46341af c7f2831 6934440 c390c71 6934440 847ea5c 6934440 847ea5c 6934440 847ea5c 007a2ef 8b608ba 007a2ef 46341af 3f43fd8 46341af 44d0a2b 483c136 ef03766 2de4f9d ef03766 79df262 d4a2c6b 79df262 ef03766 79df262 ef03766 1589e5a 46341af 558d0d7 6b1cf92 558d0d7 1589e5a 0dfc33a 792ab6c 558d0d7 f3997e2 558d0d7 e8d6409 6934440 ed6c657 3005416 483c136 e8d6409 6b1cf92 e8d6409 6934440 0dfc33a b4fa09a 60c6cbb b4fa09a 4308466 e1fc821 6b1cf92 e1fc821 ef03766 0f49c61 ef03766 8b608ba e81aab6 8b608ba ef03766 8b608ba e1fc821 e81aab6 e1fc821 e8d6409 0005a21 e1fc821 4325715 4d41e48 4325715 4d41e48 0005a21 4325715 44d0a2b 8b608ba |
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
<script lang="ts">
import { onMount, tick } from 'svelte';
import ShareWithCommunity from "$lib/ShareWithCommunity.svelte";
let promptTxt = '';
let isLoading = false;
let isUploading = false;
let isOutputControlAdded = false;
let isSuccessfulGeneration = false;
let drawingBoard: any;
let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D | null;
let noiseTs: DOMHighResTimeStamp;
let imageTs: DOMHighResTimeStamp;
let drawNextImage: () => void;
let interval: ReturnType<typeof setInterval>;
let canvasSize = 400;
let canvasContainerEl: HTMLDivElement;
let fileInput: HTMLInputElement;
let sketchEl: HTMLCanvasElement;
let isShowSketch = false;
let outputImgs: CanvasImageSource[] = [];
let outputFiles: {sketch: File, generations: File[]};
const animImageDuration = 500 as const;
const animNoiseDuration = 3000 as const;
async function drawNoise() {
if (!ctx) {
return;
}
const imageData = ctx.createImageData(canvas.width, canvas.height);
const pix = imageData.data;
for (let i = 0, n = pix.length; i < n; i += 4) {
const c = 7;
pix[i] = 40 * Math.random() * c; // Set a random gray
pix[i + 1] = 40 * Math.random() * c; // Set a random gray
pix[i + 2] = 40 * Math.random() * c; // Set a random gray
pix[i + 3] = 255; // 100% opaque
}
const bitmap = await createImageBitmap(imageData);
const duration = performance.now() - noiseTs;
ctx.globalAlpha = Math.min(duration, animNoiseDuration) / animNoiseDuration;
ctx.drawImage(bitmap, 0, 0, canvasSize, canvasSize);
if (isLoading) {
window.requestAnimationFrame(drawNoise);
}
}
function drawImage(image: CanvasImageSource) {
if (!ctx) {
return;
}
const duration = performance.now() - imageTs;
ctx.globalAlpha = Math.min(duration, animImageDuration) / animImageDuration;
ctx.drawImage(image, 0, 0, canvasSize, canvasSize);
if (duration < animImageDuration) {
window.requestAnimationFrame(() => drawImage(image));
}
}
async function getCanvasSnapshot(
canvas: HTMLCanvasElement
): Promise<{ imgFile: File; imgBitmap: ImageBitmap }> {
const canvasDataUrl = canvas.toDataURL('png');
const res = await fetch(canvasDataUrl);
const blob = await res.blob();
const imgFile = new File([blob], 'canvas shot.png', { type: 'image/png' });
const imgData = canvas.getContext('2d')!.getImageData(0, 0, canvasSize, canvasSize);
const imgBitmap = await createImageBitmap(imgData);
return { imgFile, imgBitmap };
}
async function submitRequest() {
if (!promptTxt) {
return alert('Please add prompt');
}
if (!canvas || !ctx) {
return;
}
if (interval) {
clearInterval(interval);
}
isLoading = true;
isShowSketch = false;
isSuccessfulGeneration = false;
copySketch();
// start noise animation
noiseTs = performance.now();
drawNoise();
const { imgFile: sketch, imgBitmap: initialSketchBitmap } = await getCanvasSnapshot(canvas);
const form = new FormData();
form.append('prompt', promptTxt);
form.append('strength', '0.85');
form.append('image', sketch);
try {
const response = await fetch('https://sdb.pcuenca.net/i2i', {
method: 'POST',
body: form
});
const json = JSON.parse(await response.text());
const { images: imagesBase64Strs }: { images: string[] } = json;
if (!imagesBase64Strs.length) {
return alert(
'All the results were flagged. Please try again with diffeerent sketch + prompt'
);
}
outputImgs = (await Promise.all(
imagesBase64Strs.map(async (imgBase64Str) => {
const imgEl = new Image();
imgEl.src = `data:image/png;base64, ${imgBase64Str}`;
// await image.onload
await new Promise((resolve, _) => {
imgEl.onload = () => resolve(imgEl);
});
return imgEl;
})
)) as CanvasImageSource[];
outputImgs.push(initialSketchBitmap);
outputFiles = {
sketch,
generations: (await Promise.all(
imagesBase64Strs.map(async (imgBase64Str) => {
const dataUrl = `data:image/jpeg;base64, ${imgBase64Str}`;
const res: Response = await fetch(dataUrl);
const blob: Blob = await res.blob();
const imgId = Date.now() % 200;
const fileName = `diffuse-the-rest-${imgId}.jpeg`;
return new File([blob], fileName, { type: 'image/jpeg' });
})
)) as File[]
};
isShowSketch = true;
let i = 0;
imageTs = performance.now();
drawImage(outputImgs[i % outputImgs.length]);
drawNextImage = () => {
if (interval) {
clearInterval(interval);
}
imageTs = performance.now();
i = i + 1;
drawImage(outputImgs[i % outputImgs.length]);
};
interval = setInterval(() => {
i = i + 1;
imageTs = performance.now();
drawImage(outputImgs[i % outputImgs.length]);
}, 2500);
if (!isOutputControlAdded) {
addOutputControl();
}
isSuccessfulGeneration = true;
} catch (err) {
console.error(err);
alert('Error happened, queue might be full. Please try again in a bit :)');
} finally {
isLoading = false;
}
}
function addOutputControl() {
const div = document.createElement('div');
div.className = 'drawing-board-control';
const btn = document.createElement('button');
btn.innerHTML = '⏯';
btn.onclick = drawNextImage;
div.append(btn);
const controlsEl = document.querySelector('.drawing-board-controls');
if (controlsEl && outputImgs.length > 1) {
controlsEl.appendChild(div);
isOutputControlAdded = true;
canvasContainerEl.onclick = () => {
if (interval) {
clearInterval(interval);
}
};
}
}
function addClearCanvasControl() {
const div = document.createElement('div');
div.className = 'drawing-board-control';
const btn = document.createElement('button');
btn.innerHTML = '🧹';
btn.onclick = () => {
ctx?.clearRect(0, 0, canvasSize, canvasSize);
outputImgs = [];
isShowSketch = false;
};
div.append(btn);
const controlsEl = document.querySelector('.drawing-board-controls');
if (controlsEl) {
controlsEl.appendChild(div);
}
}
function addDownloadCanvasControl() {
const div = document.createElement('div');
div.className = 'drawing-board-control';
const btn = document.createElement('button');
btn.innerHTML = '⬇️';
btn.onclick = () => {
if (!canvas) {
return;
}
const link = document.createElement('a');
const imgId = Date.now() % 200;
link.download = `diffuse-the-rest-${imgId}.png`;
link.href = canvas.toDataURL();
link.click();
};
div.append(btn);
const controlsEl = document.querySelector('.drawing-board-controls');
if (controlsEl) {
controlsEl.appendChild(div);
}
}
function copySketch() {
const context = sketchEl.getContext('2d');
//set dimensions
sketchEl.width = canvas.width;
sketchEl.height = canvas.height;
//apply the old canvas to the new one
context!.drawImage(canvas, 0, 0);
}
async function drawUploadedImg(file: File) {
if (interval) {
clearInterval(interval);
}
const imgEl = new Image();
imgEl.src = URL.createObjectURL(file);
// await image.onload
await new Promise((resolve, _) => {
imgEl.onload = () => resolve(imgEl);
});
const { width, height } = imgEl;
// keep aspect ratio
if (width == height) {
ctx?.drawImage(imgEl, 0, 0, width, height, 0, 0, canvasSize, canvasSize);
} else if (width > height) {
const canvasHeight = Math.floor((canvasSize * height) / width);
const padding = Math.floor((canvasSize - canvasHeight) / 2);
ctx?.drawImage(imgEl, 0, 0, width, height, 0, padding, canvasSize, canvasHeight);
} else {
const canvasWidth = Math.floor((canvasSize * width) / height);
const padding = Math.floor((canvasSize - canvasWidth) / 2);
ctx?.drawImage(imgEl, 0, 0, width, height, padding, 0, canvasWidth, canvasSize);
}
}
function onfImgUpload() {
const file = fileInput.files?.[0];
if (file) {
drawUploadedImg(file);
}
}
function handleDrop(e: DragEvent) {
if (!e.dataTransfer?.files) {
return;
}
e.preventDefault();
const files = Array.from(e.dataTransfer.files);
const file = files[0];
drawUploadedImg(file);
}
function handlePaste(e: ClipboardEvent) {
if (!e.clipboardData) {
return;
}
const files = Array.from(e.clipboardData.files);
if (files.length === 0) {
return;
}
e.preventDefault();
const file = files[0];
drawUploadedImg(file);
}
function onKeyDown(e: KeyboardEvent) {
if(isLoading){
return e.preventDefault();
}
if (e.code === 'Enter') {
e.preventDefault();
submitRequest();
}
}
// original: https://gist.github.com/MonsieurV/fb640c29084c171b4444184858a91bc7
function polyfillCreateImageBitmap() {
window.createImageBitmap = async function (data: ImageData): Promise<ImageBitmap> {
return new Promise((resolve, _) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = data.width;
canvas.height = data.height;
ctx!.putImageData(data, 0, 0);
const dataURL = canvas.toDataURL();
const img = document.createElement('img');
img.addEventListener('load', () => {
resolve(img as any as ImageBitmap);
});
img.src = dataURL;
});
};
}
function makeLinksTargetBlank() {
const linkEls = document.querySelectorAll('a');
for (const linkEl of linkEls) {
linkEl.target = '_blank';
}
}
async function uploadFile(file: File): Promise<string> {
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 createCommunityPost() {
isUploading = true;
const files = [outputFiles.sketch, ...outputFiles.generations];
console.log(files)
const urls = await Promise.all(files.map((f) => uploadFile(f)));
const htmlImgs = urls.map(url => `<img src="${url}" width="400" height="400">`);
const descriptionMd = `#### Prompt:
${promptTxt}
#### Sketch:
<div style="display: flex; overflow: scroll; column-gap: 0.75rem;">
${htmlImgs[0]}
</div>
#### Generations:
<div style="display: flex; flex-wrap: wrap; column-gap: 0.75rem;">
${htmlImgs.slice(1).join("\n")}
</div>`;
const params = new URLSearchParams({
title: promptTxt,
description: descriptionMd,
});
const paramsStr = params.toString();
window.open(`https://huggingface.co/spaces/huggingface/diffuse-the-rest/discussions/new?${paramsStr}`, '_blank');
isUploading = false;
}
onMount(async () => {
if (typeof createImageBitmap === 'undefined') {
polyfillCreateImageBitmap();
}
const { innerWidth: windowWidth } = window;
canvasSize = Math.min(canvasSize, Math.floor(windowWidth * 0.75));
canvasContainerEl.style.width = `${canvasSize}px`;
canvasContainerEl.style.height = `${canvasSize}px`;
sketchEl.style.width = `${canvasSize}px`;
sketchEl.style.height = `${canvasSize}px`;
await tick();
drawingBoard = new window.DrawingBoard.Board('board-container', {
size: 10,
controls: ['Color', { Size: { type: 'dropdown' } }, { DrawingMode: { filler: false } }],
webStorage: false,
enlargeYourContainer: true
});
canvas = drawingBoard.canvas;
ctx = canvas.getContext('2d');
canvas.ondragover = function (e) {
e.preventDefault();
return false;
};
addClearCanvasControl();
addDownloadCanvasControl();
makeLinksTargetBlank();
});
</script>
<svelte:head>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/drawingboard.js/0.4.2/drawingboard.css"
rel="stylesheet"
/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/drawingboard.js/0.4.2/drawingboard.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.1/iframeResizer.contentWindow.min.js"></script>
</svelte:head>
<svelte:window on:drop|preventDefault|stopPropagation={handleDrop} on:paste={handlePaste} />
<div class="flex flex-wrap gap-x-4 gap-y-2 justify-center my-8">
<canvas
class="border-[1.2px] desktop:mt-[34px] {!isShowSketch ? 'hidden' : ''}"
bind:this={sketchEl}
/>
<div class="flex flex-col items-center {isLoading ? 'pointer-events-none' : ''}">
{#if !canvas}
<div>
<p>Loading…</p>
<p>█▒▒▒▒▒▒▒▒▒</p>
</div>
{/if}
<div id="board-container" bind:this={canvasContainerEl} />
{#if canvas}
<div>
<div class="w-full flex justify-end">
<ShareWithCommunity on:createCommunityPost={createCommunityPost} {isUploading} isVisisble={isSuccessfulGeneration}/>
</div>
<div class="flex gap-x-2 mt-3 items-start justify-center {isLoading ? 'animate-pulse' : ''}">
<span
class="overflow-auto resize-y py-2 px-3 min-h-[42px] max-h-[500px] !w-[181px] whitespace-pre-wrap inline-block border border-gray-200 shadow-inner outline-none"
role="textbox"
contenteditable
style="--placeholder: 'Add prompt'"
spellcheck="false"
dir="auto"
maxlength="200"
bind:textContent={promptTxt}
on:keydown={onKeyDown}
/>
<button
on:click={submitRequest}
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-[0.555rem] px-4"
>
diffuse the f rest
</button>
</div>
<div class="mt-4">
<label class="inline border py-1 px-1.5 bg-slate-200 cursor-pointer">
<input
accept="image/*"
bind:this={fileInput}
on:change={onfImgUpload}
style="display: none;"
type="file"
/>
upload img
</label>
<p class="hidden desktop:inline mt-2 opacity-50">
pro tip: upload img by dropping on the canvas
</p>
</div>
</div>
{/if}
</div>
</div>
<article class="prose-sm px-4 md:px-12 lg:px-56 mb-8 {!canvas ? 'hidden' : ''}">
<div class="text-center">
Stable Diffusion model by [CompVis](https://huggingface.co/CompVis) and [Stability AI](https://huggingface.co/stabilityai) - Demo by 🤗 Hugging Face
Powered by [🤗 Diffusers: State-of-the-art diffusion models for image and audio generation in PyTorch](https://github.com/huggingface/diffusers). Based on [notebook by @psuraj28](https://twitter.com/psuraj28/status/1562039265126670339)
Check out [Stable Diffusion Gradio demo](https://huggingface.co/spaces/stabilityai/stable-diffusion)
</div>
### LICENSE
The model is licensed with a [CreativeML Open RAIL-M](https://huggingface.co/spaces/CompVis/stable-diffusion-license) license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please [read the license](https://huggingface.co/spaces/CompVis/stable-diffusion-license)
### Biases and content acknowledgment
Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. The model was trained on the [LAION-5B dataset](https://laion.ai/blog/laion-5b/), which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes. You can read more in the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4)
</article>
<style>
span[contenteditable]:empty::before {
content: var(--placeholder);
color: rgba(156, 163, 175);
}
</style>
|