File size: 6,521 Bytes
1c0590e
108f30f
 
 
 
1c0590e
8fce765
1c0590e
 
 
d6da254
 
108f30f
d6da254
108f30f
1c0590e
 
 
d6da254
 
db78a09
 
 
 
 
 
108f30f
ffd658d
7fb1583
db78a09
 
 
 
 
 
d6da254
db78a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6da254
 
 
 
db78a09
 
 
 
108f30f
7fb1583
e1a5fd6
 
 
 
 
 
 
 
 
 
 
 
db78a09
1c0590e
 
 
 
 
 
 
 
 
 
727ce74
 
 
 
 
b628664
727ce74
 
 
 
 
 
 
 
 
d6da254
108f30f
7fb1583
74cddec
 
 
 
 
 
 
 
 
 
 
 
e32b26d
 
 
 
b3b11fd
e32b26d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74cddec
 
108f30f
1c0590e
727ce74
 
 
 
1c0590e
 
8fce765
bf003c3
 
 
 
 
 
 
 
 
8fce765
bf003c3
 
 
 
 
 
 
8fce765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79d0fc0
2401f68
 
ffd658d
 
8fce765
 
 
 
 
 
ffd658d
 
 
 
 
8fce765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74e73b3
8fce765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4530fe2
8fce765
 
4530fe2
 
 
8fce765
 
 
 
 
 
45dab68
 
bf003c3
 
45dab68
bf003c3
 
 
 
45dab68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { json, type RequestEvent } from '@sveltejs/kit';
import puppeteer from 'puppeteer';
import { promises } from 'fs';
import { randomUUID } from 'crypto';

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

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

export async function GET({ url, params } : RequestEvent) {
  const id = params.id?.replace("@", "/")

  const full = Boolean(url.searchParams.get('full')) ?? false
  const metadata = Boolean(url.searchParams.get('metadata')) ?? false

  const model = await prisma.model.findFirst({
    where: {
      id,
    },
    select: full ? {
      id: true,
      likes: true,
      downloads: true,
      image: true,
      instance_prompt: true,
      metadata: true,
      base_model: true,
      isPublic: true,
      gallery: {
        select: {
          id: true,
          prompt: true,
          image: true,
          createdAt: true,
        },
        where: {
          isPublic: true
        },
        orderBy: {
          createdAt: 'desc'
        },
        take: 10
      },
      comments: {
        select: {
          id: true,
          createdAt: true,
          text: true,
          user: {
            select: {
              id: true,
              name: true,
              sub: true,
              picture: true,
              preferred_username: true,
            }
          }
        }
      }
    } : {
      instance_prompt: true,
      image: true,
      id: true,
      metadata: true,
      isPublic: true,
      gallery: {
        select: {
          image: true,
        },
        where: {
          isPublic: true
        },
        orderBy: {
          createdAt: 'desc'
        },
        take: 1
      },
    }
  })

  if (!model) {
    return json({
      error: {
        token: "Model params is required"
      }
    }, { status: 401 })
  }

  let infos: Record<string, string | string[]> = {};

  if (full) {
    const hf_model_request = await fetch(`https://huggingface.co/api/models/${id}`, {
      headers: {
        "Authorization": `Bearer ${process.env.SECRET_HF_TOKEN}`
      }
    })
    const hf_model_response = await hf_model_request.json();
    infos = {
      base_model: hf_model_response?.cardData?.base_model,
      license: hf_model_response?.cardData?.license,
      tags: hf_model_response?.cardData?.tags,
    }
  }

  // get puppeteer screenshot
  if (!model.metadata && metadata && model?.isPublic) {
    const browser = await puppeteer.launch({
      headless: true,
      defaultViewport: {
        width: 1920,
        height: 1080,
      },
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
      ],
      ignoreDefaultArgs: ['--disable-extensions']
    }).catch((err) => console.error(err))

    if (browser) {
      const page = await browser.newPage();
      await page.goto("https://lorastudio.co/metadata/models/" + id, {
        waitUntil: 'networkidle0',
      });
    
      const buffer = await page.screenshot({
        type: 'png',
      });
    
      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() + "_" + "metadata" + model.id.replace("/", "-") + ".png"
      await promises.writeFile(`${process.env.PUBLIC_FILE_UPLOAD_DIR}/${file_name_formatted}`, buffer)
    
      await prisma.model.update({
        where: {
          id,
        },
        data: {
          metadata: file_name_formatted
        }
      })
    
      await browser.close();
    }

  }

  return json({
    model: {
      ...model,
      infos
    }
  })
}

export async function POST({ params, cookies, fetch } : RequestEvent) {
  const token = cookies.get('hf_access_token')
  if (!token) {
    return json({
      error: {
        token: "Token is required"
      }
    }, { status: 401 })
  }

  const user = await tokenIsAvailable(token)
  if (!user || !process.env.SECRET_HF_ADMIN?.includes(user.sub)) {
    return json({
      error: {
        token: "Wrong castle fam :^)"
      }
    }, { status: 401 })
  }

  const id = params.id?.replace("@", "/")

  const model = await prisma.model.findFirst({
    where: {
      id,
    }
  })

  if (!model) {
    return json({
      error: {
        token: "Model not found"
      }
    }, { status: 404 })
  }

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

  const base_model = hf_model.tags.find((tag: string) => tag.startsWith("base_model:"))?.split(":")[1] ?? null

  await prisma.model.update({
    where: {
      id,
    },
    data: {
      isPublic: true,
      instance_prompt: hf_model?.cardData?.instance_prompt,
      ...(base_model ? {
        base_model: base_model
      } : {}
      )
    }
  })

  return json({
    success: true
  })
}

export async function DELETE({ params, cookies } : RequestEvent) {
  const token = cookies.get('hf_access_token')
  if (!token) {
    return json({
      error: {
        token: "Token is required"
      }
    }, { status: 401 })
  }

  const user = await tokenIsAvailable(token)
  if (!user || !process.env.SECRET_HF_ADMIN?.includes(user.sub)) {
    return json({
      error: {
        token: "Wrong castle fam :^)"
      }
    }, { status: 401 })
  }

  const id = params.id?.replace("@", "/")

  const model = await prisma.model.findFirst({
    where: {
      id,
    }
  })

  if (!model) {
    return json({
      error: {
        token: "Model not found"
      }
    }, { status: 404 })
  }

  await prisma.model.update({
    where: {
      id,
    },
    data: {
      isPublic: false,
    }
  })

  return json({
    success: true
  })
}

export async function PATCH({ request, params } : 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 id = params.id?.replace("@", "/")

  const model = await prisma.model.findFirst({
    where: {
      id,
    }
  })

  if (!model) {
    return json({
      error: {
        token: "Model not found"
      }
    }, { status: 404 })
  }

  const body = await request.json()

  await prisma.model.update({
    where: {
      id,
    },
    data: {
      ...body
    }
  })

  return json({
    success: true
  })
}