File size: 6,786 Bytes
560b99e
 
66ed450
be26971
d11af81
66ed450
a6e7e8f
3b048e4
a392773
5496efb
5636b7a
6cb70cf
 
b2fc3c0
 
 
 
 
 
 
423b87b
 
560b99e
3d2cb9e
423b87b
3b048e4
40e1c88
423b87b
 
809d458
423b87b
 
b2fc3c0
3b048e4
 
 
 
7d4e291
5636b7a
7d4e291
3b048e4
 
 
 
b4efffa
be26971
b4efffa
5636b7a
b4efffa
3b048e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b92d91
3b048e4
 
 
 
 
 
a6e7e8f
b4efffa
3b048e4
 
 
 
 
b4efffa
d11af81
b4efffa
 
3b048e4
 
 
 
 
 
 
 
 
dec096c
61988b7
b4efffa
7c37442
5636b7a
7c37442
a6e7e8f
5636b7a
 
331e32b
5e4af9b
a6e7e8f
 
809d458
331e32b
dec096c
57fd5c8
331e32b
a392773
a6e7e8f
 
 
 
 
 
b4efffa
5636b7a
b4efffa
a6e7e8f
 
 
 
 
 
 
331e32b
 
 
a6e7e8f
 
57fd5c8
a6e7e8f
 
 
 
b4efffa
5636b7a
b4efffa
a6e7e8f
 
6a839c1
a6e7e8f
 
 
 
 
 
 
61988b7
 
 
 
 
 
 
 
c3e8635
5bdc2c3
c3e8635
61988b7
 
b4efffa
61988b7
b4efffa
423b87b
61988b7
 
423b87b
61988b7
 
d982737
 
6cb70cf
61988b7
a6e7e8f
3b048e4
35d6c3b
 
 
 
c3e8635
 
 
35d6c3b
 
 
3b048e4
a6e7e8f
 
 
 
 
 
 
 
 
 
 
 
 
560b99e
 
1d701d3
e5b9b7e
a6e7e8f
1d701d3
b4efffa
3b048e4
 
 
 
 
a6e7e8f
0dca05c
d6e3c15
1d701d3
66ed450
 
423b87b
1d701d3
a439de3
32561d8
8dabd94
7d4e291
423b87b
304976c
32561d8
7c37442
 
66ed450
304976c
423b87b
32561d8
66ed450
 
 
 
3b048e4
66ed450
 
5496efb
3b048e4
66ed450
560b99e
 
 
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
<script lang="ts">
	import Cursor from '$lib/Cursor.svelte';
	import Frame from '$lib/Frame.svelte';
	import PaintFrame from '$lib/PaintFrame.svelte';
	import PaintCanvas from '$lib/PaintCanvas.svelte';
	import Menu from '$lib/Menu.svelte';
	import PromptModal from '$lib/PromptModal.svelte';
	import { COLORS, FRAME_SIZE } from '$lib/constants';
	import { PUBLIC_WS_INPAINTING } from '$env/static/public';
	import type { PromptImgKey } from '$lib/types';
	import { Status } from '$lib/types';
	import { LiveObject } from '@liveblocks/client';

	import {
		loadingState,
		currZoomTransform,
		maskEl,
		selectedRoomID,
		isRenderingCanvas
	} from '$lib/store';
	import { useMyPresence, useObject, useOthers } from '$lib/liveblocks';
	import { nanoid } from 'nanoid';

	const myPresence = useMyPresence({ addToHistory: true });
	const others = useOthers();
	let showModal = false;
	function getKey(position: { x: number; y: number }): PromptImgKey {
		return `${position.x}_${position.y}`;
	}

	const promptImgStorage = useObject('promptImgStorage');

	$: isLoading = $myPresence?.status === Status.loading || $isRenderingCanvas || false;
	function onShowModal(e: CustomEvent) {
		if (isLoading) return;
		showModal = e.detail.showModal;
		if (showModal) {
			myPresence.update({
				status: Status.prompting
			});
		} else {
			myPresence.update({
				status: Status.ready
			});
		}
	}

	function onPaint() {
		showModal = false;
		generateImage();
	}
	function canPaint(position: { x: number; y: number }): boolean {
		if (!$others) return true;
		let canPaint = true;
		for (const { presence } of $others) {
			if (
				position.x < presence.frame.x + FRAME_SIZE &&
				position.x + FRAME_SIZE > presence.frame.x &&
				position.y < presence.frame.y + FRAME_SIZE &&
				position.y + FRAME_SIZE > presence.frame.y
			) {
				// can paint if presence is only  dragging
				if (presence.status === Status.ready || presence.status === Status.dragging) {
					canPaint = true;
					continue;
				}
				canPaint = false;
				break;
			}
		}
		return canPaint;
	}

	function clearStateMsg(t = 5000) {
		setTimeout(() => {
			$loadingState = '';
		}, t);
	}
	async function generateImage() {
		if (isLoading) return;
		const prompt = $myPresence.currentPrompt;
		const position = $myPresence.frame;
		$loadingState = 'Pending';
		if (!canPaint(position)) {
			$loadingState = 'Someone is already painting here';
			myPresence.update({
				status: Status.ready
			});
			clearStateMsg();
			return;
		}
		const imageKey = getKey(position);
		const room = $selectedRoomID || 'default';
		console.log('Generating...', prompt, position);
		myPresence.update({
			status: Status.loading
		});
		const sessionHash = crypto.randomUUID();
		const base64Crop = $maskEl.toDataURL('image/png');

		const hashpayload = {
			fn_index: 0,
			session_hash: sessionHash
		};

		const datapayload = {
			data: [base64Crop, prompt, 0.75, 7.5, 40, 'patchmatch', room, imageKey]
		};

		const websocket = new WebSocket(PUBLIC_WS_INPAINTING);
		// websocket.onopen = async function (event) {
		// 	websocket.send(JSON.stringify({ hash: sessionHash }));
		// };
		websocket.onclose = (evt) => {
			if (!evt.wasClean) {
				$loadingState = 'Error';
				myPresence.update({
					status: Status.ready
				});
			}
		};
		websocket.onmessage = async function (event) {
			try {
				const data = JSON.parse(event.data);
				$loadingState = '';
				switch (data.msg) {
					case 'send_hash':
						websocket.send(JSON.stringify(hashpayload));
						break;
					case 'send_data':
						$loadingState = 'Sending Data';
						websocket.send(JSON.stringify({ ...hashpayload, ...datapayload }));
						break;
					case 'queue_full':
						$loadingState = 'Queue full';
						websocket.close();
						myPresence.update({
							status: Status.ready
						});
						return;
					case 'estimation':
						const { rank, queue_size } = data;
						$loadingState = `On queue ${rank}/${queue_size}`;
						break;
					case 'process_generating':
						$loadingState = data.success ? 'Generating' : 'Error';
						break;
					case 'process_completed':
						try {
							const params = data.output.data[0] as {
								is_nsfw: boolean;
								image: {
									url: string;
									filename: string;
								};
							};
							const isNSWF = params.is_nsfw;
							if (isNSWF) {
								throw new Error('NFSW');
							}
							// const imgBlob = await base64ToBlob(imgBase64);
							const promptImgParams = {
								prompt,
								imgURL: params.image.filename,
								position,
								date: new Date().getTime(),
								id: nanoid(),
								room: room
							};
							// const imgURL = await uploadImage(imgBlob, promptImgParams);

							$promptImgStorage.set(imageKey, new LiveObject(promptImgParams));
							// $promptImgStorage.set(imageKey, promptImgParams);

							console.log(params.image.url);
							$loadingState = data.success ? 'Complete' : 'Error';
							clearStateMsg();
							myPresence.update({
								status: Status.ready,
								currentPrompt: ''
							});
						} catch (err) {
							const tError = err as Error;
							$loadingState = tError?.message;
							myPresence.update({
								status: Status.ready
							});
							clearStateMsg(10000);
						}
						websocket.close();
						return;
					case 'process_starts':
						$loadingState = 'Processing';
						break;
				}
			} catch (e) {
				console.error(e);
				$loadingState = 'Error';
			}
		};
	}
</script>

<!-- Show the current user's cursor location -->
<div class="text touch-none pointer-events-none">
	{$loadingState}
</div>
{#if showModal}
	<PromptModal
		on:paint={onPaint}
		initPrompt={$myPresence?.currentPrompt}
		on:showModal={onShowModal}
	/>
{/if}
<div class="fixed top-0 left-0 z-0 w-screen h-screen min-h-[600px]">
	<PaintCanvas />

	<main class="z-10 relative">
		<!-- When others connected, iterate through others and show their cursors -->
		{#if $others}
			{#each [...$others] as { connectionId, presence } (connectionId)}
				{#if (presence?.status === Status.loading || presence?.status === Status.prompting || presence?.status === Status.masking) && presence?.frame}
					<Frame
						status={presence.status}
						position={presence?.frame}
						prompt={presence?.currentPrompt}
						transform={$currZoomTransform}
					/>
				{/if}
				{#if presence?.cursor}
					<Cursor
						color={COLORS[1 + (connectionId % (COLORS.length - 1))]}
						position={presence?.cursor}
						transform={$currZoomTransform}
					/>
				{/if}
			{/each}
		{/if}
		<PaintFrame transform={$currZoomTransform} on:showModal={onShowModal} />
	</main>
</div>
<div class="fixed bottom-0 md:bottom-16 left-0 right-0 z-10 my-2">
	<Menu {isLoading} on:showModal={onShowModal} />
</div>

<style lang="postcss" scoped>
</style>