File size: 2,229 Bytes
eb29a95
17aecfb
8fce765
 
98b0aa6
 
 
 
8fce765
 
 
 
 
 
b0186cb
8fce765
 
 
98b0aa6
b34e9b1
 
1c0590e
b34e9b1
17aecfb
 
8fce765
17aecfb
eb29a95
17aecfb
 
 
b0186cb
17aecfb
f3ad218
1c0590e
17aecfb
 
b1a4d81
 
8fce765
b1a4d81
eb29a95
b1a4d81
 
 
b34e9b1
98b0aa6
 
17aecfb
98b0aa6
 
9fd8477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { json, type RequestEvent } from '@sveltejs/kit';
import prisma from '$lib/prisma';

import { tokenIsAvailable } from '$lib/utils';

/** @type {import('./$types').RequestHandler} */

export async function GET(request : RequestEvent) {
  const token = request.cookies.get('hf_access_token')
  let IS_ADMIN = !!token

  if (token) {
    const user = await tokenIsAvailable(token)
    if (user) {
      IS_ADMIN = process?.env?.SECRET_HF_ADMIN ? process?.env?.SECRET_HF_ADMIN.includes(user.sub) : false
    }
  }

  const page = parseInt(request.url.searchParams.get('page') || '0')
  const filter = request.url.searchParams.get('filter') || 'hotest'
  const search = request.url.searchParams.get('search') || ''
  const limit = parseInt(request.url.searchParams.get('limit') || '20')

  const cards = await prisma.model.findMany({
    where: {
      ...(IS_ADMIN ? {} : { isPublic: true }),
      OR: [
        { id: { contains: search } },
      ]
    },
    orderBy: {
      ...(filter === 'hotest' ? { downloads: 'desc' } : filter === 'likes' ? { likes: 'desc' } : { createdAt: 'desc' })
    },
    skip: page * limit,
    take: limit,
  })

  const total_reposId = await prisma.model.count({
    where: {
      ...(IS_ADMIN ? {} : { isPublic: true }),
      OR: [
        { id: { contains: search } },
      ]
    },
  })

  return json({
    cards,
    total_items: total_reposId
  })
}

export async function PATCH({ request } : RequestEvent) {
  const headers = Object.fromEntries(request.headers.entries());

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

  const models = await prisma.model.findMany({
    where: {
      isPublic: true,
    }
  })

  let total_updates = 0;

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

    await prisma.model.update({
      where: {
        id: model.id
      },
      data: {
        likes: hf_model.likes,
        downloads: hf_model.downloads,
      }
    })
    total_updates++
  }

  return json({
    message: `Updated ${total_updates} models`
  })
}