Public
HTTP
Forked from substrate/illustratedPrimer
substrate-template.web.val.run
July 10, 2024
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
import promptHeader from "https://esm.town/v/substrate/promptHeader";
import { ComputeText, GenerateImage, sb, Substrate } from "npm:substrate";
export default async function handler(req: Request): Promise<Response> {
const prompt = new URL(req.url).searchParams.get("prompt") || "bullfrog";
const substrate = new Substrate({ apiKey: Deno.env.get("SUBSTRATE_API_KEY") });
const desc = new ComputeText({
prompt:
`create a description of an image of ${prompt}. we'll use this description to generate an image. be concise and terse. Include details on the background, angle & framing, and style.`,
});
const image = new GenerateImage({ prompt: desc.future.text });
const caption = new ComputeText({ prompt: "describe this", image_uris: [image.future.image_uri] });
const stream = await substrate.stream(caption);
async function* content() {
yield new TextEncoder().encode(
`${
promptHeader(prompt)
}<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:16px;padding:16px;">`,
);
for await (const event of stream) {
if (event.object === "node.result") {
if (event.data.text) {
yield new TextEncoder().encode(
`<div style="background-color:#f0f0f0;border-radius:8px;padding:16px;box-shadow:0 2px 4px rgba(0,0,0,0.1);">${event.data.text}</div>`,
);
} else if (event.data.image_uri) {
yield new TextEncoder().encode(
`<div style="background-color:#f0f0f0;border-radius:8px;padding:16px;box-shadow:0 2px 4px rgba(0,0,0,0.1);"><img src="${event.data.image_uri}" style="width:100%;height:auto;object-fit:contain;" alt="Generated image"/></div>`,
);
}
}
}
yield new TextEncoder().encode(`</div>`);
}
const responseStream = ReadableStream.from(content());
return new Response(responseStream, { headers: { "Content-Type": "text/html" } });
}
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!
July 10, 2024