File size: 9,156 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | import fs from 'node:fs';
import path from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { DATA_DIR } from '../db/database.js';
import { callLLMForRole, extractCleanJson } from './llmService.js';
import type { AssetAnalysisProfile, AssetItem } from '@olokaflow/shared';
const execFileAsync = promisify(execFile);
/**
* Analyzes an image, SVG, video, or audio asset using Multimodal Vision LLM (with rich heuristic fallback).
*/
export async function analyzeAssetMultimodal(
asset: Pick<
AssetItem,
'id' | 'name' | 'type' | 'relativePath' | 'mimeType' | 'width' | 'height' | 'durationSec' | 'brandTag' | 'sourceUrl'
>,
projectContextHint = ''
): Promise<AssetAnalysisProfile> {
const fullPath = path.join(DATA_DIR, asset.relativePath);
const now = new Date().toISOString();
const orientation =
asset.width > asset.height
? 'landscape'
: asset.height > asset.width
? 'portrait'
: 'square';
const aspectRatio =
orientation === 'portrait' ? '9:16' : orientation === 'landscape' ? '16:9' : '1:1';
// Default baseline heuristic profile
const fallbackProfile: AssetAnalysisProfile = {
description: `Hình ảnh/tư liệu "${asset.name}" (${asset.type.toUpperCase()} ${asset.width}x${asset.height})`,
shortCaption: asset.name,
tags: asset.name
.toLowerCase()
.split(/[^a-z0-9àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ]+/)
.filter((t) => t.length >= 2),
categories: [asset.type],
dominantColors: ['#1e2bfa', '#0f172a', '#f8fafc'],
colorMood: 'modern',
composition: {
subjectPosition: 'center',
hasText: false,
textContent: asset.brandTag ? [asset.brandTag] : [],
backgroundType: asset.mimeType.includes('png') || asset.mimeType.includes('svg') ? 'transparent' : 'photo',
orientation,
aspectRatio,
},
semantics: {
objects: [asset.name],
scene: 'product-showcase',
mood: 'professional',
industry: 'general',
brand: asset.brandTag || '',
suitableFor:
asset.type === 'svg' || /logo|icon|brand/i.test(asset.name)
? ['logo-outro', 'brand-watermark', 'hero-showcase']
: ['hero-showcase', 'feature-card', 'b-roll'],
},
videoSegments:
asset.type === 'video'
? buildDefaultVideoSegments(asset.durationSec || 12, asset.name)
: [],
analyzedByModel: 'heuristic-analyzer',
analyzedAt: now,
};
if (!fs.existsSync(fullPath)) {
return fallbackProfile;
}
try {
if (asset.type === 'image' || asset.type === 'svg') {
const buf = fs.readFileSync(fullPath);
if (asset.type === 'svg') {
const svgText = buf.toString('utf8');
const textMatches = Array.from(svgText.matchAll(/<text[^>]*>([\s\S]*?)<\/text>/gi)).map(
(m) => m[1].replace(/<[^>]+>/g, '').trim()
);
const hexColors = Array.from(new Set(svgText.match(/#[0-9a-fA-F]{6}\b/g) || [])).slice(0, 5);
if (hexColors.length) fallbackProfile.dominantColors = hexColors;
if (textMatches.length) {
fallbackProfile.composition.hasText = true;
fallbackProfile.composition.textContent = textMatches;
}
fallbackProfile.composition.backgroundType = 'transparent';
fallbackProfile.semantics.suitableFor = ['logo-outro', 'brand-watermark'];
return fallbackProfile;
}
// Send Base64 image to Vision Analyzer LLM if size <= 6MB
if (buf.length <= 6 * 1024 * 1024) {
const dataUri = `data:${asset.mimeType};base64,${buf.toString('base64')}`;
const visionResp = await callLLMForRole({
role: 'vision_analyzer',
maxTokens: 900,
temperature: 0.2,
messages: [
{
role: 'system',
content: `Bạn là Chuyên gia Phân tích Hình ảnh & Thương hiệu bằng Vision AI cho hệ thống dựng video HyperFrames.
Hãy phân tích bức ảnh được gửi và trả về DUY NHẤT một JSON object theo cấu trúc:
{
"description": "Mô tả chi tiết bằng tiếng Việt (chủ thể, màu sắc, bối cảnh)",
"shortCaption": "Tóm tắt ngắn gọn 5-10 từ",
"tags": ["tu-khoa-1", "tu-khoa-2"],
"dominantColors": ["#hex1", "#hex2", "#hex3"],
"colorMood": "warm | cool | dark | vibrant | minimal",
"composition": {
"subjectPosition": "center | left | right | full",
"hasText": true,
"textContent": ["Toàn bộ chữ OCR đọc được trên bao bì/ảnh/logo"],
"backgroundType": "transparent | solid | gradient | photo | complex"
},
"semantics": {
"objects": ["vật thể chính"],
"scene": "product-studio | ui-screenshot | lifestyle | portrait | chart",
"mood": "luxury | tech | energetic | trustworthy",
"industry": "ngành hàng",
"brand": "Tên thương hiệu nhận diện được trên ảnh (hoặc rỗng)",
"suitableFor": ["Hook", "Product_Intro", "Key_Feature", "CTA", "logo-outro"]
}
}`,
},
{
role: 'user',
content: [
{
type: 'text',
text: `Phân tích bức ảnh này (Tên file: "${asset.name}", Ngữ cảnh dự án: "${projectContextHint || 'Video quảng cáo/giới thiệu'}").`,
},
{
type: 'image_url',
image_url: { url: dataUri },
},
],
},
],
});
if (visionResp && visionResp.content) {
const parsed = extractCleanJson<Partial<AssetAnalysisProfile>>(visionResp.content, {});
return {
...fallbackProfile,
...parsed,
composition: {
...fallbackProfile.composition,
...(parsed.composition || {}),
orientation,
aspectRatio,
},
semantics: {
...fallbackProfile.semantics,
...(parsed.semantics || {}),
brand: parsed.semantics?.brand || asset.brandTag || '',
},
analyzedByModel: visionResp.usedModelId,
analyzedAt: now,
};
}
}
}
if (asset.type === 'video') {
const durationSec = await probeMediaDurationSec(fullPath, asset.durationSec || 12);
fallbackProfile.videoSegments = buildDefaultVideoSegments(durationSec, asset.name);
fallbackProfile.description = `Video B-Roll "${asset.name}" dài ${durationSec.toFixed(1)}s được chia thành ${fallbackProfile.videoSegments.length} phân đoạn chuyển động.`;
return fallbackProfile;
}
if (asset.type === 'audio') {
const durationSec = await probeMediaDurationSec(fullPath, asset.durationSec || 30);
const bpm = 120;
const beatInterval = 60 / bpm;
const beats: number[] = [];
for (let t = 0; t < Math.min(durationSec, 60); t += beatInterval) {
beats.push(Number(t.toFixed(2)));
}
fallbackProfile.audioProfile = {
bpm,
genre: 'modern-electronic',
mood: 'upbeat',
energy: 'high',
beats,
};
return fallbackProfile;
}
} catch (err: any) {
console.warn(`[AssetAnalysis] Fallback used for ${asset.name}:`, err.message);
}
return fallbackProfile;
}
function buildDefaultVideoSegments(durationSec: number, name: string) {
const total = Math.max(4, durationSec || 12);
const segCount = Math.min(4, Math.max(2, Math.floor(total / 3.5)));
const segLen = Number((total / segCount).toFixed(1));
return Array.from({ length: segCount }, (_, idx) => {
const start = Number((idx * segLen).toFixed(1));
const end = Number(Math.min(total, (idx + 1) * segLen).toFixed(1));
const labels = [
'Cảnh mở đầu (Establishing Shot) thu hút ánh nhìn',
'Cận cảnh chi tiết sản phẩm / thao tác chính (Hero Action)',
'Góc máy động năng lượng cao (Dynamic B-Roll Highlight)',
'Khoảnh khắc hoàn thiện / kết quả thực tế (Payoff Shot)',
];
return {
start,
end,
description: `${labels[idx % labels.length]} — ${name}`,
energy: (idx === 1 || idx === 2 ? 'high' : 'medium') as 'low' | 'medium' | 'high',
visualStyle: 'cinematic-broll',
};
});
}
export async function probeMediaDurationSec(filePath: string, defaultSec = 10): Promise<number> {
try {
const isWin = process.platform === 'win32';
const cmd = isWin ? 'ffprobe.exe' : 'ffprobe';
const { stdout } = await execFileAsync(
cmd,
[
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
],
{ timeout: 6000 }
);
const val = parseFloat(stdout.trim());
return Number.isFinite(val) && val > 0 ? val : defaultSec;
} catch {
return defaultSec;
}
}
|