Spaces:
Running
Running
| import { json } from '@sveltejs/kit'; | |
| import prisma from '$lib/prisma'; | |
| import { tokenIsAvailable } from '$lib/utils'; | |
| /** @type {import('./$types').RequestHandler} */ | |
| export async function POST({ request, fetch, cookies }) { | |
| const model = await request.json(); | |
| const token = cookies.get('hf_access_token') | |
| if (!token) { | |
| return json({ | |
| error: { | |
| token: "You must be logged" | |
| } | |
| }, { status: 401 }) | |
| } | |
| const is_token_available = await tokenIsAvailable(token) | |
| if (!is_token_available) { | |
| return json({ | |
| error: { | |
| token: "Invalid token" | |
| } | |
| }, { status: 401 }) | |
| } | |
| // get model on hugging face | |
| const res = await fetch(`https://huggingface.co/api/models?id=${model.id}&sort=likes7d`) | |
| const data = await res.json(); | |
| if (data?.error || !data?.[0]) { | |
| return json({ | |
| error: { | |
| id: "Model not found on Hugging Face" | |
| } | |
| }, { status: 404 }) | |
| } | |
| // check model.image is valid url and is an image | |
| const imageRes = await fetch(model.image) | |
| const imageBlob = await imageRes.blob() | |
| const isImage = imageBlob.type.startsWith("image/") | |
| const isValidUrl = imageRes.status === 200 | |
| if (!isImage || !isValidUrl) { | |
| return json({ | |
| error: { | |
| image: "Invalid image url" | |
| } | |
| }, { status: 400 }) | |
| } | |
| await prisma.model.create({ | |
| data: { | |
| id: model.id, | |
| image: model.image, | |
| likes: data?.[0]?.likes, | |
| downloads: data?.[0]?.downloads, | |
| likes7d: data?.[0]?.trendingScore, | |
| isPublic: false, | |
| } | |
| }) | |
| return json({ | |
| success: true | |
| }) | |
| } | |