-
Notifications
You must be signed in to change notification settings - Fork 2
/
route.ts
182 lines (131 loc) · 6.14 KB
/
route.ts
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
import { NextResponse, NextRequest } from 'next/server';
export const maxDuration = 100; // This function can run for a maximum of 100 seconds
export const dynamic = 'force-dynamic';
const texttoimageURL = "https://api.segmind.com/v1/sdxl1.0-txt2img";
const texttoimageAPIKEY = process.env.SEGMIND_API_KEY;
const chat_gpt3_url = "https://api.openai.com/v1/chat/completions"
const gpt3_headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
}
export const POST = async (req: NextRequest, res: Response) => {
const { text, style, imagecount } = await req.json();
console.log("text: ", text);
console.log("style: ", style);
console.log("imagecount: ", imagecount);
async function fetchIllustratorPrompts(prompt) {
// let retries = 0;
let currentAttempt = 0;
const maxRetryAttempts = 3;
let success = false;
while (currentAttempt < maxRetryAttempts && !success) {
try {
// Define the payload for the chat model
const messages = [
{
role: "system",
content:
"You are an expert author who can read children's stories and create short briefs for an illustrator, providing specific instructions, ideas, or guidelines for the illustrations you want them to create.",
},
{ role: "user", content: prompt },
];
const chatgptPayload = {
model: "gpt-3.5-turbo-16k",
messages: messages,
temperature: 1.3,
max_tokens: 2000,
top_p: 1,
stop: ["###"],
};
const response = await fetch(chat_gpt3_url, {
headers: gpt3_headers,
method: "POST",
body: JSON.stringify(chatgptPayload),
cache: 'no-cache'
});
// console.log("responseJson ",await response.json());
if (!response.ok) throw new Error("GPT-3 API fetch error");
const responseJson = await response.json();
console.log("responseJson ", responseJson)
console.log("message choices ",responseJson.choices[0].message.content.trim())
const output = JSON.parse(
responseJson.choices[0].message.content.trim()
);
success = true;
return output;
} catch (err) {
currentAttempt++;
console.log(`Error on retry ${currentAttempt} parsing response or fetching data: `, err);
if (currentAttempt === maxRetryAttempts) {
console.log("Max retries reached");
return null;
}
}
}
// If max retries are reached without a successful response, return null
return null;
}
function generatePrompt(text, count) {
const promptPrefix = `${JSON.stringify(text)}
------------------------------------
Generate ${count} short briefs as a list from the above story to give as input to an illustrator to generate relevant children's story illustrations.
Strictly add no common prefix to briefs. Strictly generate each brief as a single sentence that contains all the necessary information.
Strictly output your response in a JSON list format, adhering to the following sample structure:`;
const sampleOutput = { illustrations: Array(count).fill("...") };
const promptPostinstruction = `\nOutput:`;
return (
promptPrefix + JSON.stringify(sampleOutput) + promptPostinstruction
);
}
const prompt = generatePrompt(text, imagecount);
try {
const illustratorPrompts = await fetchIllustratorPrompts(prompt);
console.log("illustratorPrompts ", illustratorPrompts)
if (!illustratorPrompts || !illustratorPrompts.illustrations) {
throw new Error('Failed to fetch illustrator prompts');
}
const images = [];
for (const illustrationText of illustratorPrompts.illustrations) {
// Generate a random seed between 400000 and 500000
const randomSeed = Math.floor(Math.random() * (500000 - 400000 + 1)) + 400000;
const requestBody = {
prompt: illustrationText,
negative_prompt: "ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, disfigured, deformed, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft",
style: style,
samples: 1,
scheduler: "UniPC",
num_inference_steps: 25,
guidance_scale: 8,
strength: 0.2,
high_noise_fraction: 0.8,
// seed: "468685",
seed: randomSeed,
img_width: 1024,
img_height: 1024,
refiner: true,
base64: true,
};
console.log(requestBody)
const response = await fetch(texttoimageURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': texttoimageAPIKEY,
},
body: JSON.stringify(requestBody),
});
// console.log("response ",response);
if (!response.ok) {
throw new Error("Error with generating Illustrations");
}
// Assuming the response from the API is in image/jpeg format
const responseData = await response.json();
const base64Image = responseData.image;
images.push(base64Image);
}
return NextResponse.json({ images: images }, { status: 200 });
} catch (error) {
console.error(error)
return NextResponse.json({ "message": `ERROR: Could not generate images for the text` }, { status: 500 });
}
}