Spaces:
No application file
No application file
| import type { NextApiRequest, NextApiResponse } from "next"; | |
| import { VALID_MODELS, validateModel, validateApiKey } from "../../lib/config"; | |
| import type { EditRequestBody } from "../../lib/types"; | |
| export default async function handler(req: NextApiRequest, res: NextApiResponse) { | |
| res.setHeader("Content-Type", "application/json"); | |
| if (req.method !== "POST") { | |
| return res.status(405).json({ error: "Method not allowed" }); | |
| } | |
| const hfApiKey = process.env.HF_API_KEY; | |
| if (!validateApiKey(hfApiKey)) { | |
| return res.status(500).json({ error: "Invalid or missing Hugging Face API key" }); | |
| } | |
| const model = VALID_MODELS.DREAM_VAE; | |
| if (!validateModel(model)) { | |
| return res.status(500).json({ error: "Invalid DreamVAE model configuration" }); | |
| } | |
| let body: EditRequestBody; | |
| try { | |
| body = req.body as EditRequestBody; | |
| } catch { | |
| return res.status(400).json({ error: "Invalid JSON body" }); | |
| } | |
| const { operation, trackId, params = {} } = body; | |
| if (!operation || !trackId) { | |
| return res.status(400).json({ error: "operation and trackId are required" }); | |
| } | |
| try { | |
| const payload = { | |
| inputs: { | |
| track_id: trackId, | |
| operation, | |
| params, | |
| }, | |
| }; | |
| const hfUrl = `https://api-inference.huggingface.co/models/${encodeURIComponent(model)}`; | |
| const response = await fetch(hfUrl, { | |
| method: "POST", | |
| headers: { | |
| Authorization: `Bearer ${hfApiKey}`, | |
| "Content-Type": "application/json", | |
| Accept: "application/json", | |
| }, | |
| body: JSON.stringify(payload), | |
| }); | |
| if (!response.ok) { | |
| const errText = await response.text().catch(() => ""); | |
| return res.status(response.status).json({ | |
| error: "DreamVAE request failed", | |
| details: errText || response.statusText, | |
| }); | |
| } | |
| const result = await response.json(); | |
| return res.status(200).json({ | |
| model, | |
| operation, | |
| trackId, | |
| result, | |
| }); | |
| } catch (e: any) { | |
| return res.status(500).json({ | |
| error: "Unexpected error during editing", | |
| details: e?.message ?? "Unknown error", | |
| }); | |
| } | |
| } | |