digo_big / services /geminiService.ts
didigo's picture
Add files using upload-large-folder tool
7fab18f verified
import { GoogleGenAI } from "@google/genai";
import { Dynasty } from '../types';
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif'];
const convertToJpeg = (base64Source: string): Promise<{ mimeType: string, data: string }> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('Failed to create canvas context'));
return;
}
// Fill white background to handle transparent PNGs converting to JPEG
ctx.fillStyle = '#FFFFFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
const jpegUrl = canvas.toDataURL('image/jpeg', 0.85);
const data = jpegUrl.replace(/^data:image\/jpeg;base64,/, "");
resolve({ mimeType: 'image/jpeg', data });
};
img.onerror = () => reject(new Error('Failed to load image for conversion'));
img.src = base64Source;
});
};
export const generateHanfuTryOn = async (
base64Image: string,
dynasty: Dynasty,
customizations: string[]
): Promise<string> => {
// Extract mime type from base64 string
// Use a broader regex to catch types like image/svg+xml or image/avif
const mimeTypeMatch = base64Image.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,/);
const currentMimeType = mimeTypeMatch ? mimeTypeMatch[1] : '';
let finalMimeType = currentMimeType;
let finalData = base64Image.replace(/^data:image\/[a-zA-Z0-9.+-]+;base64,/, "");
// If MIME type is not natively supported by Gemini, convert to JPEG
if (currentMimeType && !SUPPORTED_MIME_TYPES.includes(currentMimeType)) {
try {
console.log(`Format ${currentMimeType} not supported by API. Converting to JPEG...`);
const converted = await convertToJpeg(base64Image);
finalMimeType = converted.mimeType;
finalData = converted.data;
} catch (e) {
console.warn("Image conversion failed, attempting to send original.", e);
}
}
let dynastyPrompt = "";
switch (dynasty) {
case Dynasty.Tang:
dynastyPrompt = "Tang Dynasty style Hanfu (Qixiong Ruqun), luxurious, colorful silk, high waist skirt";
break;
case Dynasty.Song:
dynastyPrompt = "Song Dynasty style Hanfu (Beizi), elegant, subtle colors, slender silhouette, sophisticated";
break;
case Dynasty.Ming:
dynastyPrompt = "Ming Dynasty style Hanfu (Mamian skirt and Aoqun), dignified, gold embroidery, structured";
break;
}
const customizationPrompt = customizations.join(", ");
const prompt = `Change the outfit of the person in this image to a ${dynastyPrompt}. ${customizationPrompt ? `Accessories: ${customizationPrompt}.` : ''} Keep the face, pose, and body shape unchanged. Photorealistic, high quality.`;
try {
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash-image',
contents: {
parts: [
{
inlineData: {
mimeType: finalMimeType || 'image/jpeg',
data: finalData,
},
},
{
text: prompt,
},
],
},
});
// Extract image from response
let generatedImageBase64 = null;
// Gemini 2.5 Flash Image returns parts. We need to find the image part.
if (response.candidates && response.candidates[0] && response.candidates[0].content && response.candidates[0].content.parts) {
for (const part of response.candidates[0].content.parts) {
if (part.inlineData && part.inlineData.data) {
generatedImageBase64 = part.inlineData.data;
break;
}
}
}
if (!generatedImageBase64) {
console.error("Unexpected response structure:", response);
throw new Error("No image data found in the response.");
}
return `data:image/png;base64,${generatedImageBase64}`;
} catch (error) {
console.error("Gemini API Error:", error);
throw error;
}
};