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
import * as fal from "npm:@fal-ai/serverless-client";
fal.config({
credentials: Deno.env.get("FAL_KEY"),
});
export const realtimeGenerateImageHandler = async (req: Request): Promise<Response> => {
const { prompt, model } = await req.json();
const body = new ReadableStream({
async start(controller) {
const delimiter = '--boundary--';
const write = (msg: any) => {
controller.enqueue(new TextEncoder().encode(msg));
controller.enqueue(new TextEncoder().encode(delimiter));
};
try {
console.log("Starting real-time image generation...");
const result = await new Promise((resolve, reject) => {
const connection = fal.realtime.connect(model, {
onResult: (result) => {
console.log("Received result from fal.realtime.connect");
resolve(result);
},
onError: (error) => {
console.error("Error during real-time image generation:", error);
reject(error);
},
});
console.log("Sending prompt to fal.realtime.connect");
connection.send({
prompt,
num_images: 4,
});
});
console.log("Generation completed. Result:", result);
if (result.images && Array.isArray(result.images)) {
const imageUrls = result.images.map((imageObj: any) => {
if (imageObj && imageObj.url) {
return imageObj.url; // Assuming there's a 'url' property in the image object
} else {
console.warn("Invalid image object:", imageObj);
return null; // or handle invalid case accordingly
}
});
write(JSON.stringify({ urls: imageUrls }));
} else {
console.error("Invalid or missing 'images' property in the result. Result:", result);
write(JSON.stringify({ error: "Invalid response received from the server." }));
}
console.log("All image data sent");
} catch (error) {
console.error("Error in realtimeGenerateImageHandler:", error);
write(JSON.stringify({ error: error.message }));
}
controller.close();
console.log("ReadableStream closed");
},
});
return new Response(body);
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
June 17, 2024