-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
85 lines (76 loc) · 1.93 KB
/
index.js
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
import { useState } from 'react';
import Head from 'next/head';
import Image from 'next/image';
import styles from '../styles/Home.module.css';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export default function Home() {
const [prediction, setPrediction] = useState(null);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('/api/predictions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: e.target.prompt.value,
}),
});
let prediction = await response.json();
if (response.status !== 201) {
setError(prediction.detail);
return;
}
setPrediction(prediction);
while (prediction.status !== 'succeeded' && prediction.status !== 'failed') {
await sleep(1000);
const response = await fetch('/api/predictions/' + prediction.id);
prediction = await response.json();
if (response.status !== 200) {
setError(prediction.detail);
return;
}
console.log({ prediction });
setPrediction(prediction);
}
};
return (
<div className={styles.container}>
<Head>
<title>Replicate + Next.js</title>
</Head>
<p>
Dream something with{' '}
<a href='https://replicate.com/stability-ai/stable-diffusion'>
stability-ai/stable-diffusion
</a>
:
</p>
<form className={styles.form} onSubmit={handleSubmit}>
<input
type='text'
name='prompt'
placeholder='Enter a prompt to display an image'
/>
<button type='submit'>Go!</button>
</form>
{error && <div>{error}</div>}
{prediction && (
<div>
{prediction.output && (
<div className={styles.imageWrapper}>
<Image
fill
src={prediction.output[prediction.output.length - 1]}
alt='output'
sizes='100vw'
/>
</div>
)}
<p>status: {prediction.status}</p>
</div>
)}
</div>
);
}