File size: 2,226 Bytes
c9a7b70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549506b
 
 
 
 
c9a7b70
 
 
 
 
 
 
 
 
 
549506b
c9a7b70
 
549506b
c9a7b70
 
 
 
 
 
549506b
c9a7b70
549506b
 
 
 
 
 
 
 
 
 
c9a7b70
 
 
 
 
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
// latent-consistency/lcm-lora-sdv1-5
/** @type {import('./$types').RequestHandler} */

import { json } from '@sveltejs/kit';
// import moment from 'moment';
import prisma from '$lib/prisma';

export async function POST({ request, params }) {
  const headers = Object.fromEntries(request.headers.entries());
  const slug= params?.slug?.replace("@", "/")

  if (headers["x-hf-token"] !== process.env.SECRET_HF_TOKEN) {
    return Response.json({
      message: "Wrong castle fam :^)"
    }, { status: 401 });
  }

  const response = await fetch(`https://huggingface.co/api/models/${slug}`)
  const model = await response.json();

  const hasImages = model?.siblings?.filter((sibling: Record<string, string>) => sibling?.rfilename.endsWith(".png") || sibling?.rfilename.endsWith(".jpeg") || sibling?.rfilename.endsWith(".jpg"))
  if (hasImages.length > 0) {
    model.image = hasImages[1]?.rfilename ? `https://huggingface.co/${model.id}/resolve/main/${hasImages[1]?.rfilename}` : `https://huggingface.co/${model.id}/resolve/main/${hasImages[0]?.rfilename}`
  } else {
    const hasReadme = model?.siblings?.find((sibling: Record<string, string>) => sibling?.rfilename === "README.md")
    if (hasReadme) {
      const readmeRes = await fetch(`https://huggingface.co/${model.id}/raw/main/README.md`)
      const readme = await readmeRes.text().catch(() => null)
      if (!readme) {
        return json({
          message: "No readme"
        }, { status: 404 })
      }
      const imageRegex = /!\[.*\]\((.*)\)/
      let image = readme.match(imageRegex)?.[1]
  
      if (!image) {
        return json({
          message: "No image found"
        }, { status: 404 })
      }
      image = image.replace(/&#x2F;/g, "/")
      if (image.startsWith("http")) model.image = image
      else model.image = `https://huggingface.co/${model.id}/resolve/main/${image.replace("./", "")}`
    }
  }

  await prisma.model.create({
    data: {
      id: model.id,
      image: model.image,
      likes: model.likes,
      downloads: model.downloads,
      isPublic: true,
      instance_prompt: model?.cardData?.instance_prompt,
    }
  }).catch(() => {})

  return json({
    message: `Successfully added the model ${model.id}`,
  })
}