File size: 2,484 Bytes
be02369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

const MCP_SERVER_URL = 'https://black-forest-labs-flux-1-kontext-dev.hf.space/run/FLUX_1_Kontext_Dev_infer';

/**
 * Edits a bonsai image using the FLUX.1 Kontext MCP tool.
 * @param imageBase64 The base64 encoded string of the input image.
 * @param prompt The text prompt describing the desired edit.
 * @returns A base64 encoded string of the edited image, or null if an error occurs.
 */
export const editBonsaiWithKontext = async (
    imageBase64: string,
    prompt: string
): Promise<string | null> => {
    try {
        const inputImage = `data:image/jpeg;base64,${imageBase64}`;

        // Based on the provided documentation and common Gradio API structure.
        // The payload is an object with a 'data' array containing the arguments in order.
        // The order of arguments is assumed from the Python example: 
        // input_image, prompt, seed, randomize_seed, guidance_scale
        const payload = {
            data: [
                inputImage,       // input_image
                prompt,           // prompt
                -1,               // seed (-1 for random)
                true,             // randomize_seed
                2.5,              // guidance_scale
            ]
        };

        const response = await fetch(MCP_SERVER_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        if (!response.ok) {
            const errorBody = await response.text();
            console.error("MCP Server Error:", response.status, errorBody);
            throw new Error(`Request failed with status ${response.status}`);
        }

        const result = await response.json();

        // Gradio API responses typically wrap the output in a 'data' array.
        // The edited image is expected to be the first element.
        if (result && Array.isArray(result.data) && result.data.length > 0) {
            const outputImage = result.data[0];
            // The output is often a data URI. We need to extract the base64 part.
            if (typeof outputImage === 'string' && outputImage.startsWith('data:image/')) {
                return outputImage.split(',')[1];
            }
        }
        
        console.error("Invalid response format from MCP server:", result);
        return null;

    } catch (error) {
        console.error("Error calling MCP tool:", error);
        return null;
    }
};