Spaces:
Sleeping

File size: 7,644 Bytes
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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 };
}