File size: 15,098 Bytes
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
1ccbe14
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73ae169
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ccbe14
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3e7f87
 
276f2ce
b3e7f87
 
276f2ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3e7f87
 
 
 
71d640e
b3e7f87
71d640e
b3e7f87
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dc1071
 
 
 
 
71d640e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ccbe14
71d640e
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/**

 * API ROUTE: /api/hf-process

 * 

 * HuggingFace model processing endpoint for the Nano Banana Editor.

 * Handles image editing and generation using HuggingFace models.

 * 

 * Supported Models:

 * - black-forest-labs/FLUX.1-Kontext-dev: Image editing with context understanding

 * - Qwen/Qwen-Image-Edit: Powerful image editing model  

 * - black-forest-labs/FLUX.1-dev: Text-to-image generation

 * 

 * IMPORTANT LIMITATIONS:

 * - These models only accept SINGLE images for editing

 * - MERGE operations require Nano Banana (Gemini API) which accepts multiple images

 * - Text-to-image (FLUX.1-dev) doesn't require input images

 */

import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { HfInference } from "@huggingface/inference";

// Configure Next.js runtime
export const runtime = "nodejs";

// Set maximum execution time for AI operations
export const maxDuration = 60;

/**

 * Available HuggingFace models with their capabilities

 */
const HF_MODELS = {
    "FLUX.1-Kontext-dev": {
        id: "black-forest-labs/FLUX.1-Kontext-dev",
        name: "FLUX.1 Kontext",
        type: "image-to-image",
        description: "Advanced image editing with context understanding",
        supportsNodes: ["BACKGROUND", "CLOTHES", "STYLE", "EDIT", "CAMERA", "AGE", "FACE", "LIGHTNING", "POSES"],
    },
    "Qwen-Image-Edit": {
        id: "Qwen/Qwen-Image-Edit",
        name: "Qwen Image Edit",
        type: "image-to-image",
        description: "Powerful image editing and manipulation",
        supportsNodes: ["BACKGROUND", "CLOTHES", "STYLE", "EDIT", "CAMERA", "AGE", "FACE", "LIGHTNING", "POSES"],
    },
};

/**

 * Parse base64 data URL into components

 */
function parseDataUrl(dataUrl: string): { mimeType: string; data: string } | null {
    const match = dataUrl.match(/^data:(.*?);base64,(.*)$/);
    if (!match) return null;
    return {
        mimeType: match[1] || "image/png",
        data: match[2]
    };
}

/**

 * Convert base64 to Blob for HuggingFace API

 */
function base64ToBlob(base64: string, mimeType: string): Blob {
    const byteCharacters = atob(base64);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type: mimeType });
}

/**

 * Main POST handler for HuggingFace model processing

 */
export async function POST(req: NextRequest) {
    try {
        // Parse request body
        let body: {
            type: string;
            model: string;
            image?: string;
            prompt?: string;
            params?: any;
        };

        try {
            body = await req.json();
        } catch (jsonError) {
            console.error('[HF-API] Failed to parse JSON:', jsonError);
            return NextResponse.json(
                { error: "Invalid JSON in request body" },
                { status: 400 }
            );
        }

        // Get HF token from cookies
        let hfToken: string | null = null;
        try {
            const cookieStore = await cookies();
            const tokenCookie = cookieStore.get('hf_token');
            hfToken = tokenCookie?.value || null;
        } catch (error) {
            console.error('Error reading HF token:', error);
        }

        if (!hfToken) {
            return NextResponse.json(
                { error: "Please login with HuggingFace to use HF models. Click 'Login with HuggingFace' in the header." },
                { status: 401 }
            );
        }

        // Validate model selection
        const modelKey = body.model as keyof typeof HF_MODELS;
        const modelConfig = HF_MODELS[modelKey];

        if (!modelConfig) {
            return NextResponse.json(
                { error: `Invalid model: ${body.model}. Available models: ${Object.keys(HF_MODELS).join(", ")}` },
                { status: 400 }
            );
        }

        // Check for MERGE - not supported with HF models
        if (body.type === "MERGE") {
            return NextResponse.json(
                {
                    error: "MERGE operations require Nano Banana (Gemini API). HuggingFace models only accept single images. Please switch to 'Nano Banana' mode and enter your Google Gemini API key to use MERGE functionality.",
                    requiresNanoBananaPro: true
                },
                { status: 400 }
            );
        }

        // Initialize HuggingFace client
        const hf = new HfInference(hfToken);

        // Handle text-to-image generation (FLUX.1-dev)
        if (modelConfig.type === "text-to-image") {
            const prompt = body.prompt || body.params?.characterDescription || "A professional portrait photo";

            try {
                const result = await hf.textToImage({
                    model: modelConfig.id,
                    inputs: prompt,
                    parameters: {
                        num_inference_steps: 28,
                        guidance_scale: 3.5,
                    },
                });

                // Result is a Blob, convert to base64
                const resultBlob = result as unknown as Blob;
                const arrayBuffer = await resultBlob.arrayBuffer();
                const base64 = Buffer.from(arrayBuffer).toString('base64');
                const dataUrl = `data:image/png;base64,${base64}`;

                return NextResponse.json({ image: dataUrl });
            } catch (hfError: any) {
                console.error('[HF-API] Text-to-image error:', hfError);
                return NextResponse.json(
                    { error: `HuggingFace API error: ${hfError.message || 'Unknown error'}` },
                    { status: 500 }
                );
            }
        }

        // Handle image-to-image editing
        if (modelConfig.type === "image-to-image") {
            // Validate input image
            if (!body.image) {
                return NextResponse.json(
                    { error: "No input image provided. Please connect an image source to this node." },
                    { status: 400 }
                );
            }

            // Handle different image formats
            let parsed: { mimeType: string; data: string } | null = null;
            let imageUrl = body.image;

            // Try parsing as Data URL first
            parsed = parseDataUrl(imageUrl);

            // If not a data URL, handle various URL formats
            if (!parsed) {
                // Convert relative paths to absolute URLs
                if (imageUrl.startsWith('/')) {
                    const spaceHost = process.env.SPACE_HOST || 'localhost:3000';
                    const protocol = spaceHost.includes('localhost') ? 'http' : 'https';
                    imageUrl = `${protocol}://${spaceHost}${imageUrl}`;
                    console.log('[HF-API] Converted relative path to:', imageUrl);
                }

                // Fetch from HTTP(S) URL
                if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
                    try {
                        console.log('[HF-API] Fetching image from URL:', imageUrl.substring(0, 100));
                        const imageResponse = await fetch(imageUrl);
                        if (!imageResponse.ok) {
                            throw new Error(`Failed to fetch image: ${imageResponse.status}`);
                        }
                        const imageBuffer = await imageResponse.arrayBuffer();
                        const contentType = imageResponse.headers.get('content-type') || 'image/png';
                        const base64 = Buffer.from(imageBuffer).toString('base64');
                        parsed = { mimeType: contentType, data: base64 };
                    } catch (fetchErr) {
                        console.error('[HF-API] Failed to fetch image URL:', fetchErr);
                    }
                }
            }

            if (!parsed) {
                console.error('[HF-API] Invalid image format. Image starts with:', body.image?.substring(0, 50));
                return NextResponse.json(
                    { error: "Invalid image format. Expected a data URL (data:image/...) or HTTP URL. Please re-upload or reconnect your image." },
                    { status: 400 }
                );
            }

            // Build the editing prompt from parameters
            const prompts: string[] = [];
            const params = body.params || {};

            // Background modifications
            if (params.backgroundType) {
                if (params.backgroundType === "color") {
                    prompts.push(`Change the background to a solid ${params.backgroundColor || "white"} color.`);
                } else if (params.backgroundType === "custom" && params.customPrompt) {
                    prompts.push(params.customPrompt);
                } else if (params.backgroundType === "city") {
                    prompts.push(`Place the person in a ${params.citySceneType || "busy city street"} during ${params.cityTimeOfDay || "daytime"}.`);
                }
            }

            // Style application  
            if (params.stylePreset) {
                const styleMap: { [key: string]: string } = {
                    "90s-anime": "Transform into 90s anime art style",
                    "mha": "Convert into My Hero Academia anime style",
                    "dbz": "Convert into Dragon Ball Z anime style",
                    "ukiyo-e": "Convert into Japanese Ukiyo-e woodblock print style",
                    "cubism": "Convert into Cubist art style",
                    "van-gogh": "Convert into Van Gogh post-impressionist style",
                    "simpsons": "Convert into The Simpsons cartoon style",
                    "family-guy": "Convert into Family Guy animation style",
                    "pixar": "Convert into Pixar animation style",
                    "manga": "Convert into Manga style",
                };
                const styleDescription = styleMap[params.stylePreset] || `Apply ${params.stylePreset} style`;
                prompts.push(`${styleDescription} at ${params.styleStrength || 50}% intensity.`);
            }

            // Edit prompt
            if (params.editPrompt) {
                prompts.push(params.editPrompt);
            }

            // Clothing modifications
            if (params.clothesPrompt) {
                prompts.push(`Change clothing to: ${params.clothesPrompt}`);
            }

            // Age transformation
            if (params.targetAge) {
                prompts.push(`Transform the person to look ${params.targetAge} years old.`);
            }

            // Face modifications
            if (params.faceOptions) {
                const face = params.faceOptions;
                const modifications: string[] = [];
                if (face.removePimples) modifications.push("remove pimples");
                if (face.addSunglasses) modifications.push("add sunglasses");
                if (face.addHat) modifications.push("add a hat");
                if (face.changeHairstyle) modifications.push(`change hairstyle to ${face.changeHairstyle}`);
                if (face.facialExpression) modifications.push(`change expression to ${face.facialExpression}`);
                if (modifications.length > 0) {
                    prompts.push(`Face modifications: ${modifications.join(", ")}`);
                }
            }

            // Lighting effects
            if (params.lightingPrompt) {
                prompts.push(`Apply lighting: ${params.lightingPrompt}`);
            }

            // Pose modifications
            if (params.posePrompt) {
                prompts.push(`Change pose to: ${params.posePrompt}`);
            }

            const finalPrompt = prompts.length > 0
                ? prompts.join(" ")
                : body.prompt || "Enhance this image with high quality output.";

            try {
                // Convert base64 to blob for HF API
                const imageBlob = base64ToBlob(parsed.data, parsed.mimeType);

                // Use image-to-image endpoint
                const result = await hf.imageToImage({
                    model: modelConfig.id,
                    inputs: imageBlob,
                    parameters: {
                        prompt: finalPrompt,
                        num_inference_steps: 28,
                        guidance_scale: 7.5,
                        strength: 0.75,
                    },
                });

                // Convert result blob to base64
                const arrayBuffer = await result.arrayBuffer();
                const base64 = Buffer.from(arrayBuffer).toString('base64');
                const dataUrl = `data:image/png;base64,${base64}`;

                return NextResponse.json({ image: dataUrl });
            } catch (hfError: any) {
                console.error('[HF-API] Image-to-image error:', hfError);

                // Provide helpful error messages
                if (hfError.message?.includes('401') || hfError.message?.includes('unauthorized')) {
                    return NextResponse.json(
                        { error: "HuggingFace authentication failed. Please logout and login again." },
                        { status: 401 }
                    );
                }

                if (hfError.message?.includes('Model') && hfError.message?.includes('not')) {
                    return NextResponse.json(
                        { error: `Model ${modelConfig.id} is not available or requires a Pro subscription.` },
                        { status: 503 }
                    );
                }

                return NextResponse.json(
                    { error: `HuggingFace API error: ${hfError.message || 'Unknown error'}` },
                    { status: 500 }
                );
            }
        }

        return NextResponse.json(
            { error: "Unsupported operation type" },
            { status: 400 }
        );

    } catch (err: any) {
        console.error("/api/hf-process error:", err);
        return NextResponse.json(
            { error: `Failed to process: ${err?.message || 'Unknown error'}` },
            { status: 500 }
        );
    }
}

/**

 * GET handler to return available models and their capabilities

 */
export async function GET() {
    return NextResponse.json({
        models: HF_MODELS,
        note: "MERGE operations require Nano Banana (Gemini API) as it needs multi-image input which HuggingFace models don't support."
    });
}