Gertie2013 commited on
Commit
3fd0bae
·
verified ·
1 Parent(s): f2db9c0

Create pages/api/edit.ts

Browse files
Files changed (1) hide show
  1. pages/api/edit.ts +78 -0
pages/api/edit.ts ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { NextApiRequest, NextApiResponse } from "next";
2
+ import { VALID_MODELS, validateModel, validateApiKey } from "../../lib/config";
3
+ import type { EditRequestBody } from "../../lib/types";
4
+
5
+ export default async function handler(req: NextApiRequest, res: NextApiResponse) {
6
+ res.setHeader("Content-Type", "application/json");
7
+
8
+ if (req.method !== "POST") {
9
+ return res.status(405).json({ error: "Method not allowed" });
10
+ }
11
+
12
+ const hfApiKey = process.env.HF_API_KEY;
13
+ if (!validateApiKey(hfApiKey)) {
14
+ return res.status(500).json({ error: "Invalid or missing Hugging Face API key" });
15
+ }
16
+
17
+ const model = VALID_MODELS.DREAM_VAE;
18
+ if (!validateModel(model)) {
19
+ return res.status(500).json({ error: "Invalid DreamVAE model configuration" });
20
+ }
21
+
22
+ let body: EditRequestBody;
23
+ try {
24
+ body = req.body as EditRequestBody;
25
+ } catch {
26
+ return res.status(400).json({ error: "Invalid JSON body" });
27
+ }
28
+
29
+ const { operation, trackId, params = {} } = body;
30
+
31
+ if (!operation || !trackId) {
32
+ return res.status(400).json({ error: "operation and trackId are required" });
33
+ }
34
+
35
+ try {
36
+ const payload = {
37
+ inputs: {
38
+ track_id: trackId,
39
+ operation,
40
+ params,
41
+ },
42
+ };
43
+
44
+ const hfUrl = `https://api-inference.huggingface.co/models/${encodeURIComponent(model)}`;
45
+
46
+ const response = await fetch(hfUrl, {
47
+ method: "POST",
48
+ headers: {
49
+ Authorization: `Bearer ${hfApiKey}`,
50
+ "Content-Type": "application/json",
51
+ Accept: "application/json",
52
+ },
53
+ body: JSON.stringify(payload),
54
+ });
55
+
56
+ if (!response.ok) {
57
+ const errText = await response.text().catch(() => "");
58
+ return res.status(response.status).json({
59
+ error: "DreamVAE request failed",
60
+ details: errText || response.statusText,
61
+ });
62
+ }
63
+
64
+ const result = await response.json();
65
+
66
+ return res.status(200).json({
67
+ model,
68
+ operation,
69
+ trackId,
70
+ result,
71
+ });
72
+ } catch (e: any) {
73
+ return res.status(500).json({
74
+ error: "Unexpected error during editing",
75
+ details: e?.message ?? "Unknown error",
76
+ });
77
+ }
78
+ }