File size: 1,899 Bytes
eb29a95
 
 
d6da254
eb29a95
 
 
7b25d55
eb29a95
7b25d55
eb29a95
7b25d55
 
 
 
 
 
 
 
eb29a95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6da254
 
 
 
 
 
 
eb29a95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6da254
 
 
 
 
eb29a95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/** @type {import('./$types').RequestHandler} */

import { UploaderDataset } from '$lib/utils/uploader';
// import { uploadImage } from '$lib/utils/upload_image';
import { json, type RequestEvent } from '@sveltejs/kit';

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

export async function POST({ request, cookies } : RequestEvent) {
  const { generation, image } = await request.json()
  const token = cookies.get('hf_access_token')

  let hf_user_id = null;

  if (token) {
    const user = await tokenIsAvailable(token)
    if (user) hf_user_id = user?.sub;
  }

  if (!generation?.model?.id) {
    return json({
      error: {
        token: "A model id is required"
      }
    }, { status: 400 })
  }

  if (!generation?.inputs) {
    return json({
      error: {
        token: "An inputs is required"
      }
    }, { status: 400 })
  }

  const blob = await fetch(image)
    .then((res) => res.blob())
    .then((blob) => blob)
    .catch((error) => {
      return json({
        error: error.message,
      }, { status: 400 })
    })

  // const success = await uploadImage({
  //   name: generation.inputs,
  //   data: image
  // })

  // console.log(success)

  const success: {
    ok: boolean,
    path?: string | undefined
  } = await UploaderDataset(blob as Blob, generation.inputs)

  if (!success.ok) {
    return json({
      error: {
        token: "Error uploading image"
      }
    }, { status: 400 })
  }
  
  const gallery = prisma.gallery.create({
    data: {
      image: success.path as string,
      prompt: generation.inputs,
      user: {
        connect: {
          sub: hf_user_id
        }
      },
      model: {
        connect: {
          id: generation.model.id
        }
      },
    }
  })
  .catch((error) => {
    console.log(error)
  })

  return json({
    message: "Successfully generated image",
    gallery
  })
}