import { GoogleGenAI, Modality, HarmSeverity } from "@google/genai";
// Ensure the API key is available in the environment variables
if (!process.env.API_KEY) {
throw new Error("API_KEY environment variable not set");
}
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const PROMPT = `Transform this image into a simple, child-friendly coloring book page. The output must have only bold, thick, black outlines and a pure white background. Remove all shading, color, and complex details. The final image should be clean, clear, and easy for a young child to color.`;
export async function generateColoringPage(
base64Image: string,
mimeType: string
): Promise {
try {
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash-image-preview',
contents: {
parts: [
{
inlineData: {
data: base64Image,
mimeType: mimeType,
},
},
{
text: PROMPT,
},
],
},
config: {
responseModalities: [Modality.IMAGE, Modality.TEXT],
},
});
// Find the first image part in the response
const imagePart = response.candidates?.[0]?.content?.parts?.find(
(part) => part.inlineData
);
if (imagePart && imagePart.inlineData) {
return imagePart.inlineData.data;
} else {
// Check for text part which might contain an explanation for failure
const textPart = response.candidates?.[0]?.content?.parts?.find(
(part) => part.text
);
const safetyReason = response.candidates?.[0]?.finishReason;
const safetyRatings = response.candidates?.[0]?.safetyRatings;
let errorMessage = "Failed to generate image. The model did not return an image part.";
if (textPart?.text) {
errorMessage += ` Model response: ${textPart.text}`;
}
// FIX: Use HarmSeverity enum for type-safe comparison instead of a string literal to resolve the type error.
if (safetyReason === 'SAFETY' || (safetyRatings && safetyRatings.some(r => r.severity !== HarmSeverity.NEGLIGIBLE))) {
errorMessage = "Image generation failed due to safety settings. Please try a different image.";
}
throw new Error(errorMessage);
}
} catch (error) {
console.error("Error generating coloring page:", error);
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred during image generation.");
}
}