import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import { UPLOADS_DIR, logUsage } from '../db/database.js'; import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js'; import { saveAndAnalyzeAsset } from './assetSearchService.js'; import type { AspectRatio, AssetItem } from '@olokaflow/shared'; export async function generateReferenceImageForScene(params: { projectId: string; sceneIndex: number; sceneTitle: string; imagePrompt: string; aspectRatio: AspectRatio; primaryColor?: string; bgColor?: string; }): Promise<{ imageUrl: string; asset: AssetItem }> { const { projectId, sceneIndex, sceneTitle, imagePrompt, aspectRatio } = params; const width = aspectRatio === '9:16' ? 768 : aspectRatio === '16:9' ? 1280 : 1024; const height = aspectRatio === '9:16' ? 1344 : aspectRatio === '16:9' ? 720 : 1024; const targets = resolveTargetsForRole('image_gen'); for (const target of targets) { const { profile, modelId } = target; if (!profile.baseUrl || !profile.apiKey) continue; const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol); const startTime = Date.now(); try { let imgBuffer: Buffer | null = null; if (profile.protocol === 'huggingface' || baseUrl.includes('huggingface.co')) { const hfUrl = baseUrl.endsWith(modelId) ? baseUrl : `${baseUrl}/${modelId}`; const resp = await fetch(hfUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${profile.apiKey}`, ...profile.customHeaders, }, body: JSON.stringify({ inputs: `${imagePrompt}, ultra-clean professional studio art direction, high contrast, no watermark`, parameters: { width, height }, }), signal: AbortSignal.timeout(45000), }); if (!resp.ok) { throw new Error(`HF Image API HTTP ${resp.status}`); } imgBuffer = Buffer.from(await resp.arrayBuffer()); } else { const sizeStr = aspectRatio === '9:16' ? '1024x1792' : aspectRatio === '16:9' ? '1792x1024' : '1024x1024'; const resp = await fetch(`${baseUrl}/images/generations`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${profile.apiKey}`, ...profile.customHeaders, }, body: JSON.stringify({ model: modelId || 'dall-e-3', prompt: imagePrompt, n: 1, size: sizeStr, }), signal: AbortSignal.timeout(45000), }); if (!resp.ok) { throw new Error(`OpenAI Image API HTTP ${resp.status}`); } const json = (await resp.json()) as any; const b64 = json.data?.[0]?.b64_json; const remoteUrl = json.data?.[0]?.url; if (b64) { imgBuffer = Buffer.from(b64, 'base64'); } else if (remoteUrl) { const r2 = await fetch(remoteUrl); imgBuffer = Buffer.from(await r2.arrayBuffer()); } } if (imgBuffer && imgBuffer.length > 256) { const assetId = `ast-gen-${crypto.randomUUID().slice(0, 8)}`; const fileName = `${assetId}-scene-${sceneIndex + 1}.png`; fs.writeFileSync(path.join(UPLOADS_DIR, fileName), imgBuffer); logUsage({ projectId, profileId: profile.id, modelId, role: 'image_gen', imagesCount: 1, durationMs: Date.now() - startTime, }); const asset = await saveAndAnalyzeAsset({ id: assetId, projectId, name: `AI Ref Cảnh #${sceneIndex + 1} (${sceneTitle.slice(0, 24)})`, type: 'image', source: 'ai_generated', relativePath: `uploads/${fileName}`, publicUrl: `/media/uploads/${fileName}`, mimeType: 'image/png', sizeBytes: imgBuffer.length, width, height, projectContextHint: imagePrompt, }); return { imageUrl: asset.publicUrl, asset }; } } catch (err: any) { console.warn(`[ImageGenService] Failed on "${profile.name}": ${err.message}`); } } // Deterministic High-Contrast Vector Art Card Fallback (when API key is not configured yet) const assetId = `ast-svg-${crypto.randomUUID().slice(0, 8)}`; const fileName = `${assetId}-scene-${sceneIndex + 1}.svg`; const primary = params.primaryColor || '#1e2bfa'; const bg = params.bgColor || '#090d16'; const safeTitle = (sceneTitle || `Scene 0${sceneIndex + 1}`) .replace(/[<>&"']/g, '') .slice(0, 38); const safeSub = (imagePrompt || 'HyperFrames Motion Showcase') .replace(/[<>&"']/g, '') .slice(0, 64); const svgContent = ` 0${sceneIndex + 1} ${safeTitle} ${safeSub} `; const svgBuf = Buffer.from(svgContent, 'utf8'); fs.writeFileSync(path.join(UPLOADS_DIR, fileName), svgBuf); const asset = await saveAndAnalyzeAsset({ id: assetId, projectId, name: `Ref Visual Cảnh #${sceneIndex + 1}`, type: 'svg', source: 'ai_generated', relativePath: `uploads/${fileName}`, publicUrl: `/media/uploads/${fileName}`, mimeType: 'image/svg+xml', sizeBytes: svgBuf.length, width, height, projectContextHint: imagePrompt, }); return { imageUrl: asset.publicUrl, asset }; }