import fs from 'node:fs'; import path from 'node:path'; import { db, DATA_DIR } from '../db/database.js'; import { analyzeAssetMultimodal } from './assetAnalysisService.js'; import type { AssetItem, ScenePacket, Project } from '@olokaflow/shared'; function rowToAsset(row: any): AssetItem { let analysis = {}; let embedding: number[] = []; try { analysis = JSON.parse(row.analysis_json || '{}'); } catch {} try { embedding = JSON.parse(row.embedding_json || '[]'); } catch {} return { id: row.id, projectId: row.project_id || null, name: row.name, type: row.type, source: row.source, sourceUrl: row.source_url || '', relativePath: row.relative_path, publicUrl: row.public_url, mimeType: row.mime_type, sizeBytes: Number(row.size_bytes || 0), width: Number(row.width || 1080), height: Number(row.height || 1080), durationSec: Number(row.duration_sec || 0), collection: row.collection || 'general', brandTag: row.brand_tag || '', analysisStatus: row.analysis_status || 'ready', analysis: analysis as any, embedding, createdAt: row.created_at, }; } export function listAssets(projectId?: string): AssetItem[] { const rows = projectId ? db .prepare('SELECT * FROM assets WHERE project_id = ? OR project_id IS NULL ORDER BY created_at DESC') .all(projectId) : db.prepare('SELECT * FROM assets ORDER BY created_at DESC').all(); return rows.map(rowToAsset); } export function getAssetById(id: string): AssetItem | null { const row = db.prepare('SELECT * FROM assets WHERE id = ?').get(id); return row ? rowToAsset(row) : null; } export function deleteAssetById(id: string): boolean { const existing = getAssetById(id); if (!existing) return false; try { const fullPath = path.join(DATA_DIR, existing.relativePath); if (fs.existsSync(fullPath)) fs.unlinkSync(fullPath); } catch {} const res = db.prepare('DELETE FROM assets WHERE id = ?').run(id); return res.changes > 0; } export function buildAssetSearchableText(asset: Partial): string { const a = asset.analysis; const parts = [ asset.name || '', asset.brandTag || '', asset.collection || '', a?.description || '', a?.shortCaption || '', ...(a?.tags || []), ...(a?.composition?.textContent || []), ...(a?.semantics?.objects || []), a?.semantics?.brand || '', a?.semantics?.industry || '', a?.semantics?.scene || '', ]; return parts.filter(Boolean).join(' ').toLowerCase(); } /** * Generates a fast 64-dimensional semantic n-gram embedding vector for cosine similarity matching. */ export function computeSemanticVector(text: string, dims = 64): number[] { const vec = new Array(dims).fill(0); const clean = (text || '') .toLowerCase() .replace(/[^\p{L}\p{N}\s]/gu, ' ') .trim(); if (!clean) return vec; const words = clean.split(/\s+/); for (const word of words) { let h = 2166136261; for (let i = 0; i < word.length; i++) { h ^= word.charCodeAt(i); h = Math.imul(h, 16777619); } const idx = Math.abs(h) % dims; vec[idx] += 1.0; // Trigrams for partial Vietnamese/English word matching for (let i = 0; i <= word.length - 3; i++) { const tri = word.slice(i, i + 3); let th = 5381; for (let j = 0; j < tri.length; j++) { th = (th * 33) ^ tri.charCodeAt(j); } vec[Math.abs(th) % dims] += 0.5; } } const norm = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0)); return norm > 0 ? vec.map((v) => Number((v / norm).toFixed(4))) : vec; } export function cosineSimilarity(a: number[], b: number[]): number { if (!a?.length || !b?.length || a.length !== b.length) return 0; let dot = 0; let normA = 0; let normB = 0; for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; normA += a[i] * a[i]; normB += b[i] * b[i]; } const denom = Math.sqrt(normA) * Math.sqrt(normB); return denom > 0 ? dot / denom : 0; } export async function saveAndAnalyzeAsset(params: { id: string; projectId?: string | null; name: string; type: 'image' | 'svg' | 'video' | 'audio'; source: AssetItem['source']; sourceUrl?: string; relativePath: string; publicUrl: string; mimeType: string; sizeBytes: number; width?: number; height?: number; durationSec?: number; collection?: string; brandTag?: string; projectContextHint?: string; }): Promise { const now = new Date().toISOString(); const baseAsset = { id: params.id, projectId: params.projectId || null, name: params.name, type: params.type, source: params.source, sourceUrl: params.sourceUrl || '', relativePath: params.relativePath, publicUrl: params.publicUrl, mimeType: params.mimeType, sizeBytes: params.sizeBytes, width: params.width || 1080, height: params.height || 1080, durationSec: params.durationSec || 0, collection: params.collection || 'general', brandTag: params.brandTag || '', }; const analysis = await analyzeAssetMultimodal(baseAsset, params.projectContextHint); const resolvedBrand = analysis.semantics?.brand || params.brandTag || ''; const searchable = buildAssetSearchableText({ ...baseAsset, brandTag: resolvedBrand, analysis, }); const embedding = computeSemanticVector(searchable); db.prepare(` INSERT OR REPLACE INTO assets ( id, project_id, name, type, source, source_url, relative_path, public_url, mime_type, size_bytes, width, height, duration_sec, collection, brand_tag, analysis_status, analysis_json, embedding_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run( baseAsset.id, baseAsset.projectId, baseAsset.name, baseAsset.type, baseAsset.source, baseAsset.sourceUrl, baseAsset.relativePath, baseAsset.publicUrl, baseAsset.mimeType, baseAsset.sizeBytes, baseAsset.width, baseAsset.height, baseAsset.durationSec, baseAsset.collection, resolvedBrand, 'ready', JSON.stringify(analysis), JSON.stringify(embedding), now ); return getAssetById(baseAsset.id)!; } /** * Brand Provenance Guard: Checks if an asset belongs to the target brand or is brand-neutral. */ function isBrandCompatible(asset: AssetItem, promptText: string, targetBrandName = ''): boolean { const assetBrand = (asset.brandTag || asset.analysis?.semantics?.brand || '').toLowerCase().trim(); if (!assetBrand) return true; // Generic/neutral asset const lowerPrompt = promptText.toLowerCase(); const lowerTarget = targetBrandName.toLowerCase().trim(); if (lowerTarget && assetBrand.includes(lowerTarget)) return true; if (lowerPrompt.includes(assetBrand)) return true; // Asset belongs to a different named brand not mentioned in prompt -> block cross-brand contamination! return false; } /** * Matches assets to scenes using the Strict 4-Tier Asset Priority Hierarchy + Cosine Similarity. */ export function matchAssetsForScenes(params: { project: Project; scenes: ScenePacket[]; brandName?: string; }): ScenePacket[] { const { project, scenes, brandName = '' } = params; const allAssets = listAssets(project.id).filter( (a) => a.type === 'image' || a.type === 'svg' || a.type === 'video' ); if (allAssets.length === 0) return scenes; // Priority Tier 0: Manual Asset Lock Mode if (project.manualAssetLock && project.lockedAssetIds.length > 0) { const lockedPool = allAssets.filter((a) => project.lockedAssetIds.includes(a.id)); if (lockedPool.length > 0) { return scenes.map((sc, idx) => { const chosen = lockedPool[idx % lockedPool.length]; const trimSec = chosen.type === 'video' && chosen.analysis?.videoSegments?.length ? chosen.analysis.videoSegments[idx % chosen.analysis.videoSegments.length].start : 0; return { ...sc, assignedAssetIds: [chosen.id], referenceImageUrl: chosen.publicUrl, videoTrimStartSec: trimSec, }; }); } } // Priority Tier 1: Assets scraped/uploaded directly for this project const tier1ProjectAssets = allAssets.filter( (a) => a.projectId === project.id && (a.source === 'prompt_scraped' || a.source === 'website_capture' || a.source === 'upload') ); // Priority Tier 2: Trusted Brand/Product Library Assets (Filtered by Brand Provenance Guard!) const tier2BrandAssets = allAssets.filter( (a) => !tier1ProjectAssets.some((t1) => t1.id === a.id) && isBrandCompatible(a, project.prompt, brandName) ); const usedAssetIds = new Set(); return scenes.map((sc, idx) => { const sceneQueryText = `${sc.title} ${sc.narrationText} ${sc.visualDirection} ${sc.role}`; const sceneVec = computeSemanticVector(sceneQueryText); // Special rule for CTA / Outro scene: Look for brand logo or transparent product hero first if (sc.role === 'CTA' || idx === scenes.length - 1) { const logoCandidate = [...tier1ProjectAssets, ...tier2BrandAssets].find( (a) => (a.type === 'svg' || /logo|brand|icon/i.test(a.name) || a.analysis?.semantics?.suitableFor?.includes('logo-outro')) && isBrandCompatible(a, project.prompt, brandName) ); if (logoCandidate) { return { ...sc, assignedAssetIds: [logoCandidate.id], referenceImageUrl: logoCandidate.publicUrl, }; } } // Score Tier 1 first, then Tier 2 const candidatePool = tier1ProjectAssets.length > 0 ? [...tier1ProjectAssets, ...tier2BrandAssets] : tier2BrandAssets; if (candidatePool.length === 0) return sc; const scored = candidatePool .map((asset) => { const sim = cosineSimilarity(sceneVec, asset.embedding || []); const tierBonus = asset.projectId === project.id ? 0.35 : 0; const unusedBonus = usedAssetIds.has(asset.id) ? 0 : 0.22; return { asset, totalScore: sim + tierBonus + unusedBonus }; }) .sort((a, b) => b.totalScore - a.totalScore); const best = scored[0]?.asset; if (!best) return sc; usedAssetIds.add(best.id); const trimSec = best.type === 'video' && best.analysis?.videoSegments?.length ? best.analysis.videoSegments[idx % best.analysis.videoSegments.length].start : 0; return { ...sc, assignedAssetIds: [best.id], referenceImageUrl: best.publicUrl, videoTrimStartSec: trimSec, }; }); }