Download apps/server/src/services/imageGenService.ts from phucsd/olokaflow: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/services/imageGenService.ts
- Command line
-
hf download hf://spaces/phucsd/olokaflow/apps/server/src/services/imageGenService.ts
-
curl -L -o imageGenService.ts https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/services/imageGenService.ts
7.64 kB
| 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 = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}"> | |
| <defs> | |
| <linearGradient id="g1" x1="0%" y1="0%" x2="100%" y2="100%"> | |
| <stop offset="0%" stop-color="${bg}" /> | |
| <stop offset="55%" stop-color="#111827" /> | |
| <stop offset="100%" stop-color="${primary}" stop-opacity="0.65" /> | |
| </linearGradient> | |
| <radialGradient id="orb" cx="72%" cy="28%" r="50%"> | |
| <stop offset="0%" stop-color="${primary}" stop-opacity="0.55" /> | |
| <stop offset="100%" stop-color="${primary}" stop-opacity="0" /> | |
| </radialGradient> | |
| </defs> | |
| <rect width="100%" height="100%" fill="url(#g1)" /> | |
| <circle cx="${Math.round(width * 0.72)}" cy="${Math.round(height * 0.28)}" r="${Math.round(Math.min(width, height) * 0.42)}" fill="url(#orb)" /> | |
| <g stroke="rgba(255,255,255,0.07)" stroke-width="1.5"> | |
| <line x1="0" y1="${Math.round(height * 0.33)}" x2="${width}" y2="${Math.round(height * 0.33)}" /> | |
| <line x1="0" y1="${Math.round(height * 0.66)}" x2="${width}" y2="${Math.round(height * 0.66)}" /> | |
| <line x1="${Math.round(width * 0.33)}" y1="0" x2="${Math.round(width * 0.33)}" y2="${height}" /> | |
| <line x1="${Math.round(width * 0.66)}" y1="0" x2="${Math.round(width * 0.66)}" y2="${height}" /> | |
| </g> | |
| <rect x="${Math.round(width * 0.1)}" y="${Math.round(height * 0.2)}" width="${Math.round(width * 0.8)}" height="${Math.round(height * 0.6)}" rx="32" fill="rgba(15,23,42,0.72)" stroke="${primary}" stroke-width="3" /> | |
| <circle cx="${Math.round(width * 0.22)}" cy="${Math.round(height * 0.34)}" r="38" fill="${primary}" /> | |
| <text x="${Math.round(width * 0.22)}" y="${Math.round(height * 0.34 + 10)}" text-anchor="middle" fill="#ffffff" font-family="sans-serif" font-size="28" font-weight="bold">0${sceneIndex + 1}</text> | |
| <text x="${Math.round(width * 0.16)}" y="${Math.round(height * 0.50)}" fill="#ffffff" font-family="sans-serif" font-size="36" font-weight="bold">${safeTitle}</text> | |
| <text x="${Math.round(width * 0.16)}" y="${Math.round(height * 0.58)}" fill="#94a3b8" font-family="sans-serif" font-size="22">${safeSub}</text> | |
| </svg>`; | |
| 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 }; | |
| } | |