File size: 1,586 Bytes
b1a4d81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dc3d3
b1a4d81
 
79d0fc0
b1a4d81
 
eb29a95
b1a4d81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb29a95
b1a4d81
79d0fc0
 
 
b1a4d81
 
 
 
 
 
 
 
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
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
  })
}