Spaces:
Sleeping

olokaflow / apps /server /src /services /assetAnalysisService.ts
phucsd's picture
Deploy OlokaFlow Studio (Fliki Light UI + HyperFrames + OlokaTTS + Modal Cloud)
9713441 verified
Raw History Blame Contribute Delete
9.16 kB
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;
}
}