Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 2,753 Bytes
eb29a95 404baa5 eb29a95 404baa5 eb29a95 fba0083 b628664 eb29a95 b628664 eb29a95 fba0083 eb29a95 404baa5 c9a7b70 404baa5 eb29a95 c9a7b70 eb29a95 404baa5 c9a7b70 404baa5 b628664 404baa5 eb29a95 |
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 |
/** @type {import('./$types').RequestHandler} */
import { json, type RequestEvent } from '@sveltejs/kit';
import { promises } from 'fs';
import { randomUUID } from 'crypto';
import { tokenIsAvailable } from '$lib/utils';
import prisma from '$lib/prisma';
export async function POST({ request, cookies } : RequestEvent) {
const token = cookies.get('hf_access_token')
const generation = await request.json()
if (!generation?.model?.id) {
return json({
error: {
token: "A model id is required"
}
}, { status: 400 })
}
if (!generation?.inputs) {
return json({
error: {
token: "An inputs is required"
}
}, { status: 400 })
}
const model = await prisma.model.findFirst({
where: {
id: generation.model.id
},
select: {
instance_prompt: true,
}
})
const response = await fetch(process.env.SECRET_INFERENCE_API_URL + "/models/" + generation?.model?.id, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SECRET_HF_TOKEN}`,
'Content-Type': 'application/json',
['x-use-cache']: "0"
},
body: JSON.stringify({
...generation,
inputs: `${(model?.instance_prompt || "")} ${generation.inputs}`,
}),
})
.then((response) => {
if (response.status !== 200) throw new Error(response.statusText)
return response.arrayBuffer()
})
.then((response) => {
return Buffer.from(response)
})
.catch((error) => {
return {
error: error.message,
}
})
if ("error" in response) {
return json({
error: response.error
}, { status: 400 })
}
let gallery;
if (token) {
const user = await tokenIsAvailable(token)
if (user?.sub) {
const dir = await promises.opendir(process?.env?.PUBLIC_FILE_UPLOAD_DIR as string).catch(() => null)
if (!dir) await promises.mkdir(process?.env?.PUBLIC_FILE_UPLOAD_DIR as string)
const file_name_formatted = randomUUID() + "_" + generation?.inputs?.replaceAll(/[^a-zA-Z0-9]/g, "-") + ".png"
await promises.writeFile(`${process.env.PUBLIC_FILE_UPLOAD_DIR}/${file_name_formatted}`, response)
gallery = await prisma.gallery.create({
data: {
image: file_name_formatted,
prompt: generation.inputs,
isPublic: false,
user: {
connect: {
sub: user.sub
}
},
model: {
connect: {
id: generation.model.id
}
},
}
})
.catch((error) => {
console.log(error)
})
}
}
const image = Buffer.from(response).toString('base64')
return json({
image: "data:image/png;base64," + image,
gallery
})
}
|