Download apps/server/src/index.ts from phucsd/olokaflow: direct link, hf CLI and curl.
- Browser
- Download file 44.4 kB
-
https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/index.ts
- Command line
-
hf download hf://spaces/phucsd/olokaflow/apps/server/src/index.ts
-
curl -L -o index.ts https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/index.ts
44.4 kB
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import Fastify from 'fastify';
import cors from '@fastify/cors';
import multipart from '@fastify/multipart';
import fastifyStatic from '@fastify/static';
import {
db,
DATA_DIR,
PROJECTS_DIR,
UPLOADS_DIR,
seedInitialDatabase,
} from './db/database.js';
import { hashPassword } from './db/crypto.js';
import {
getVaultStatus,
syncToHuggingFaceVault,
hydrateFromHuggingFaceVaultIfNeeded,
} from './db/vaultSync.js';
import {
listAIProfiles,
saveAIProfile,
deleteAIProfile,
duplicateAIProfile,
fetchModelsFromEndpoint,
testProfileConnection,
testModelPreflight,
testModelVision,
testVoiceOrMediaEndpoint,
getRoleRoutings,
saveRoleRoutings,
} from './services/aiProfileService.js';
import {
getFramePresets,
getSceneBlueprints,
getMotionRules,
getTransitions,
getRegistryCatalogItems,
searchHyperFramesCatalog,
} from './catalog/hyperframesKnowledgeBase.js';
import { VIETNAMESE_FONTS } from './services/fontService.js';
import {
AVAILABLE_VOICES,
listAvailableVoices,
listCustomClonedVoices,
createCustomClonedVoice,
deleteCustomClonedVoice,
synthesizeSceneVoice,
buildSyllableWeightedWordTimestamps,
} from './services/voiceService.js';
import { BGM_CATALOG, SFX_CATALOG } from './services/audioMixService.js';
import { generateReferenceImageForScene } from './services/imageGenService.js';
import {
inspectBinaryMagicBytes,
scrapeWebpageUrl,
searchWebFallbackImages,
} from './services/promptAssetScraperService.js';
import {
listAssets,
getAssetById,
saveAndAnalyzeAsset,
deleteAssetById,
} from './services/assetSearchService.js';
import {
listProjects,
getProjectById,
saveProject,
deleteProjectById,
startNewProjectPipeline,
buildAndValidateProjectScenes,
applySurgicalPromptEdit,
remixProjectAspectRatio,
abortProjectPipeline,
subscribeProjectProgress,
listProjectVersions,
restoreProjectVersion,
saveProjectVersionSnapshot,
} from './agent/orchestrator.js';
import {
listRenderJobs,
startProjectRenderJob,
cancelRenderJob,
} from './services/modalRenderService.js';
const PORT = Number(process.env.PORT || 7860);
const HOST = process.env.HOST || '0.0.0.0';
async function bootstrapServer() {
seedInitialDatabase();
await hydrateFromHuggingFaceVaultIfNeeded();
// Ensure every existing project has its compiled HyperFrames index.html on disk
for (const proj of listProjects()) {
const htmlPath = path.join(PROJECTS_DIR, proj.id, 'index.html');
if (!fs.existsSync(htmlPath) && proj.scenes && proj.scenes.length > 0) {
try {
await buildAndValidateProjectScenes(proj);
} catch (err: any) {
console.warn(`[Bootstrap] Rebuild project ${proj.id} skipped:`, err.message);
}
}
}
const app = Fastify({
logger: false,
bodyLimit: 50 * 1024 * 1024, // 50MB
});
await app.register(cors, {
origin: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
});
await app.register(multipart, {
limits: {
fileSize: 50 * 1024 * 1024,
},
});
// Serve /media/* from DATA_DIR (uploads, audio_cache, renders)
await app.register(fastifyStatic, {
root: DATA_DIR,
prefix: '/media/',
decorateReply: false,
});
// ==========================================================================
// 1. AUTH & USER MANAGEMENT ROUTES (LOGIN GATE + TEAM GOVERNANCE)
// ==========================================================================
function getRequireAuthGate(): boolean {
try {
const row = db
.prepare("SELECT value_json FROM system_settings WHERE key = 'global'")
.get() as { value_json: string } | undefined;
if (!row) return false;
const parsed = JSON.parse(row.value_json);
return Boolean(parsed.requireAuthGate);
} catch {
return false;
}
}
function resolveUserFromHeader(authHeader?: string): any | null {
const token = (authHeader || '').replace(/^Bearer\s+/i, '').trim();
if (!token) return null;
try {
const sess = db
.prepare('SELECT user_id, expires_at FROM sessions WHERE token = ?')
.get(token) as { user_id: string; expires_at: string } | undefined;
if (!sess) return null;
if (new Date(sess.expires_at).getTime() < Date.now()) {
db.prepare('DELETE FROM sessions WHERE token = ?').run(token);
return null;
}
const u = db
.prepare(
'SELECT id, email, name, role, token_quota, tokens_used, created_at FROM users WHERE id = ?'
)
.get(sess.user_id) as any;
if (!u) return null;
return {
id: u.id,
email: u.email,
name: u.name,
role: u.role,
tokenQuota: u.token_quota,
tokensUsed: u.tokens_used,
createdAt: u.created_at,
};
} catch {
return null;
}
}
app.get('/api/auth/me', async (req) => {
const user = resolveUserFromHeader(req.headers.authorization);
return {
authenticated: Boolean(user),
requireAuthGate: getRequireAuthGate(),
user,
};
});
app.post('/api/auth/logout', async (req) => {
const token = (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim();
if (token) {
db.prepare('DELETE FROM sessions WHERE token = ?').run(token);
}
return { success: true };
});
app.put('/api/auth/gate', async (req) => {
const { requireAuthGate } = (req.body as any) || {};
const now = new Date().toISOString();
const row = db
.prepare("SELECT value_json FROM system_settings WHERE key = 'global'")
.get() as { value_json: string } | undefined;
const current = row ? JSON.parse(row.value_json) : {};
const updated = { ...current, requireAuthGate: Boolean(requireAuthGate) };
db.prepare(
'INSERT OR REPLACE INTO system_settings (key, value_json, updated_at) VALUES (?, ?, ?)'
).run('global', JSON.stringify(updated), now);
return {
success: true,
requireAuthGate: Boolean(requireAuthGate),
};
});
app.post('/api/auth/login', async (req, reply) => {
const { email, password } = (req.body as any) || {};
const user = db
.prepare('SELECT * FROM users WHERE email = ?')
.get((email || '').trim()) as any;
if (!user || user.password_hash !== hashPassword(password || '')) {
return reply.code(401).send({ error: 'Email hoặc mật khẩu không chính xác.' });
}
const token = `tok-${crypto.randomUUID()}`;
const now = new Date().toISOString();
const expires = new Date(Date.now() + 7 * 86400_000).toISOString();
db.prepare(
'INSERT INTO sessions (token, user_id, expires_at, created_at) VALUES (?, ?, ?, ?)'
).run(token, user.id, expires, now);
return {
token,
user: {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
tokenQuota: user.token_quota,
tokensUsed: user.tokens_used,
},
};
});
app.get('/api/admin/users', async () => {
const rows = db
.prepare(
'SELECT id, email, name, role, token_quota, tokens_used, created_at FROM users ORDER BY created_at ASC'
)
.all() as any[];
return {
requireAuthGate: getRequireAuthGate(),
users: rows.map((u) => ({
id: u.id,
email: u.email,
name: u.name,
role: u.role,
tokenQuota: u.token_quota,
tokensUsed: u.tokens_used,
createdAt: u.created_at,
})),
};
});
app.post('/api/admin/users', async (req, reply) => {
const body = (req.body as any) || {};
if (!body.email || !String(body.email).trim()) {
return reply.code(400).send({ error: 'Vui lòng nhập email thành viên.' });
}
const id = `usr-${crypto.randomUUID().slice(0, 8)}`;
const now = new Date().toISOString();
db.prepare(`
INSERT OR REPLACE INTO users (id, email, name, role, password_hash, token_quota, tokens_used, created_at)
VALUES (?, ?, ?, ?, ?, ?, 0, ?)
`).run(
id,
String(body.email).trim(),
body.name || 'Creator',
body.role || 'creator',
hashPassword(body.password || 'oloka123'),
Number(body.tokenQuota || 5000000),
now
);
return { success: true, id };
});
app.delete('/api/admin/users/:id', async (req, reply) => {
const { id } = req.params as { id: string };
if (id === 'usr-admin') {
return reply.code(400).send({ error: 'Không thể xóa tài khoản Admin gốc.' });
}
db.prepare('DELETE FROM users WHERE id = ?').run(id);
return { success: true };
});
// ==========================================================================
// 2. MULTI-PROFILE AI HUB & 4-TIER LIVE CONNECTION TESTER ROUTES
// ==========================================================================
app.get('/api/ai-profiles', async () => {
return {
profiles: listAIProfiles(false),
routings: getRoleRoutings(),
};
});
app.post('/api/ai-profiles', async (req, reply) => {
try {
const body = (req.body as any) || {};
const saved = saveAIProfile(body);
return {
success: true,
profile: saved,
profiles: listAIProfiles(false),
};
} catch (err: any) {
return reply.code(400).send({ error: err.message });
}
});
app.put('/api/ai-profiles/:id', async (req, reply) => {
try {
const { id } = req.params as { id: string };
const body = (req.body as any) || {};
const saved = saveAIProfile({ ...body, id });
return {
success: true,
profile: saved,
profiles: listAIProfiles(false),
};
} catch (err: any) {
return reply.code(400).send({ error: err.message });
}
});
app.delete('/api/ai-profiles/:id', async (req) => {
const { id } = req.params as { id: string };
deleteAIProfile(id);
return {
success: true,
profiles: listAIProfiles(false),
};
});
app.post('/api/ai-profiles/:id/duplicate', async (req, reply) => {
const { id } = req.params as { id: string };
const copy = duplicateAIProfile(id);
if (!copy) return reply.code(404).send({ error: 'Profile không tồn tại.' });
return {
success: true,
profile: copy,
profiles: listAIProfiles(false),
};
});
app.post('/api/ai-profiles/fetch-models', async (req, reply) => {
try {
const body = (req.body as any) || {};
const res = await fetchModelsFromEndpoint(body);
return {
...res,
profiles: listAIProfiles(false),
};
} catch (err: any) {
return reply.code(400).send({ error: err.message });
}
});
app.post('/api/ai-profiles/test-connection', async (req) => {
const body = (req.body as any) || {};
const result = await testProfileConnection(body);
return {
result,
profiles: listAIProfiles(false),
};
});
app.post('/api/ai-profiles/test-model', async (req) => {
const body = (req.body as any) || {};
const result = await testModelPreflight(body);
return {
result,
profiles: listAIProfiles(false),
};
});
app.post('/api/ai-profiles/test-vision', async (req) => {
const body = (req.body as any) || {};
const result = await testModelVision(body);
return {
result,
profiles: listAIProfiles(false),
};
});
app.post('/api/ai-profiles/test-media', async (req) => {
const body = (req.body as any) || {};
const result = await testVoiceOrMediaEndpoint(body);
return {
result,
profiles: listAIProfiles(false),
};
});
app.put('/api/ai-routings', async (req) => {
const { routings } = (req.body as any) || {};
const saved = saveRoleRoutings(Array.isArray(routings) ? routings : []);
return {
success: true,
routings: saved,
};
});
// ==========================================================================
// 3. HYPERFRAMES 4-TIER CATALOG & AUDIO/FONT INVENTORY ROUTES
// ==========================================================================
app.get('/api/health', async () => {
return {
status: 'ok',
service: 'olokaflow-hyperframes-studio',
vault: getVaultStatus(),
timestamp: new Date().toISOString(),
};
});
app.get('/api/voices', async () => {
const voices = await listAvailableVoices();
return { voices, customVoices: listCustomClonedVoices() };
});
app.post('/api/voices/clone', async (req, reply) => {
try {
const parts = req.parts();
let audioBuf: Buffer | null = null;
let origFilename = 'voice-sample.wav';
const fields: Record<string, string> = {};
for await (const part of parts) {
if (part.type === 'file') {
audioBuf = await part.toBuffer();
origFilename = part.filename || 'voice-sample.wav';
} else {
fields[part.fieldname] = String(part.value || '');
}
}
if (!audioBuf || audioBuf.length < 128) {
return reply
.code(400)
.send({ error: 'Vui lòng tải lên tệp âm thanh mẫu (.wav, .mp3, .m4a).' });
}
const ext = path.extname(origFilename) || '.wav';
const sampleFileName = `clone-sample-${crypto.randomUUID().slice(0, 8)}${ext}`;
const sampleAudioPath = path.join(UPLOADS_DIR, sampleFileName);
fs.writeFileSync(sampleAudioPath, audioBuf);
const created = createCustomClonedVoice({
name: fields.name || 'Giọng Clone Mới',
gender: fields.gender || 'Nam',
region: fields.region || 'Việt Nam',
description:
fields.description || 'Giọng đọc Clone cá nhân hóa từ file âm thanh mẫu',
refText: fields.refText || '',
sampleAudioPath,
samplePublicUrl: `/media/uploads/${sampleFileName}`,
fallbackVoiceId: fields.fallbackVoiceId || undefined,
});
const voices = await listAvailableVoices();
return {
success: true,
voice: created,
voices,
};
} catch (err: any) {
return reply.code(400).send({ error: err.message });
}
});
app.delete('/api/voices/custom/:id', async (req) => {
const { id } = req.params as { id: string };
deleteCustomClonedVoice(id);
const voices = await listAvailableVoices();
return {
success: true,
voices,
};
});
const getCatalogPayload = async () => {
const voices = await listAvailableVoices();
return {
framePresets: getFramePresets(),
sceneBlueprints: getSceneBlueprints(),
motionRules: getMotionRules(),
transitions: getTransitions(),
registryItems: getRegistryCatalogItems(),
voices,
bgmTracks: BGM_CATALOG,
sfxItems: SFX_CATALOG,
vietnameseFonts: VIETNAMESE_FONTS,
};
};
app.get('/api/catalog/overview', getCatalogPayload);
app.get('/api/catalog', getCatalogPayload);
app.get('/api/catalog/search', async (req) => {
const { q } = (req.query as { q?: string }) || {};
const items = await searchHyperFramesCatalog(q || '');
return { items };
});
// ==========================================================================
// 4. ASSET SCRAPING, UPLOAD & MULTIMODAL AI ANALYSIS ROUTES
// ==========================================================================
app.get('/api/assets', async (req) => {
const { projectId } = (req.query as { projectId?: string }) || {};
return { assets: listAssets(projectId) };
});
app.post('/api/assets/upload', async (req, reply) => {
const data = await req.file();
if (!data) {
return reply.code(400).send({ error: 'Không nhận được file upload.' });
}
const buf = await data.toBuffer();
const magic = inspectBinaryMagicBytes(buf);
const id = `ast-up-${crypto.randomUUID().slice(0, 8)}`;
const cleanOrig = (data.filename || 'upload')
.replace(/\.[a-z0-9]+$/i, '')
.replace(/[^a-zA-Z0-9_-]/g, '_')
.slice(0, 48);
const ext =
magic.kind !== 'unknown'
? magic.ext
: path.extname(data.filename || '.png') || '.png';
const fileName = `${id}-${cleanOrig}${ext}`;
fs.writeFileSync(path.join(UPLOADS_DIR, fileName), buf);
const kind =
magic.kind === 'video' || magic.kind === 'audio' || magic.kind === 'svg'
? magic.kind
: 'image';
const asset = await saveAndAnalyzeAsset({
id,
name: data.filename || fileName,
type: kind,
source: 'upload',
relativePath: `uploads/${fileName}`,
publicUrl: `/media/uploads/${fileName}`,
mimeType: magic.mimeType !== 'application/octet-stream' ? magic.mimeType : data.mimetype,
sizeBytes: buf.length,
width: magic.width || 1080,
height: magic.height || 1080,
});
return {
success: true,
asset,
assets: listAssets(),
};
});
app.post('/api/assets/scrape-url', async (req, reply) => {
const { url, projectId, brandTag } = (req.body as any) || {};
if (!url || !String(url).trim()) {
return reply.code(400).send({ error: 'Vui lòng nhập URL cần cào tài nguyên.' });
}
const pageRes = await scrapeWebpageUrl(String(url).trim());
if (!pageRes) {
return reply.code(400).send({
error: 'Không thể thu thập tài nguyên từ URL này (URL không hợp lệ hoặc bị chặn).',
});
}
const savedAssets = [];
for (const f of pageRes.files) {
const analyzed = await saveAndAnalyzeAsset({
...f,
projectId: projectId || null,
brandTag: brandTag || pageRes.brandNameHint || '',
projectContextHint: pageRes.pageTitle,
});
savedAssets.push(analyzed);
}
return {
success: true,
pageInfo: {
url: pageRes.url,
pageTitle: pageRes.pageTitle,
pageDescription: pageRes.pageDescription,
extractedColors: pageRes.extractedColors,
brandNameHint: pageRes.brandNameHint,
},
scrapedAssets: savedAssets,
assets: listAssets(projectId),
};
});
app.post('/api/assets/search-web', async (req, reply) => {
const { query, projectId, limit } = (req.body as any) || {};
if (!query || !String(query).trim()) {
return reply.code(400).send({ error: 'Vui lòng nhập từ khóa tìm kiếm ảnh.' });
}
const rawFiles = await searchWebFallbackImages(String(query).trim(), Number(limit || 4));
const savedAssets = [];
for (const f of rawFiles) {
const analyzed = await saveAndAnalyzeAsset({
...f,
projectId: projectId || null,
projectContextHint: String(query).trim(),
});
savedAssets.push(analyzed);
}
return {
success: true,
foundAssets: savedAssets,
assets: listAssets(projectId),
};
});
app.post('/api/assets/:id/reanalyze', async (req, reply) => {
const { id } = req.params as { id: string };
const existing = getAssetById(id);
if (!existing) return reply.code(404).send({ error: 'Không tìm thấy tài nguyên.' });
const updated = await saveAndAnalyzeAsset({
id: existing.id,
projectId: existing.projectId,
name: existing.name,
type: existing.type,
source: existing.source,
sourceUrl: existing.sourceUrl,
relativePath: existing.relativePath,
publicUrl: existing.publicUrl,
mimeType: existing.mimeType,
sizeBytes: existing.sizeBytes,
width: existing.width,
height: existing.height,
durationSec: existing.durationSec,
collection: existing.collection,
brandTag: existing.brandTag,
});
return { success: true, asset: updated };
});
app.delete('/api/assets/:id', async (req) => {
const { id } = req.params as { id: string };
deleteAssetById(id);
return { success: true, assets: listAssets() };
});
// ==========================================================================
// 5. PROJECTS, STORYBOARD REVIEW, PROMPT EDIT, QUICK-EDIT & REMIX ROUTES
// ==========================================================================
app.get('/api/projects', async () => {
return { projects: listProjects() };
});
app.post('/api/projects', async (req, reply) => {
const body = (req.body as any) || {};
if (!body.prompt || !String(body.prompt).trim()) {
return reply.code(400).send({ error: 'Vui lòng nhập Prompt mô tả video cần tạo.' });
}
const project = await startNewProjectPipeline(body);
return { success: true, project };
});
// ==========================================================================
// 5B. BATCH VIDEO FACTORY (MULTI-URL / CSV / BULK PROMPT QUEUE)
// ==========================================================================
function listEnrichedBatches(): any[] {
const rows = db
.prepare('SELECT * FROM batch_jobs ORDER BY created_at DESC LIMIT 50')
.all() as any[];
return rows.map((r) => {
const config = JSON.parse(r.config_json || '{}');
const rawItems = JSON.parse(r.items_json || '[]') as any[];
let completedCount = 0;
let failedCount = 0;
const items = rawItems.map((it) => {
const proj = it.projectId ? getProjectById(it.projectId) : null;
const projStatus = proj ? proj.status : it.status || 'queued';
const renderOutputUrl =
proj?.renderOutputUrl || proj?.latestRenderUrl || it.renderOutputUrl || '';
if (projStatus === 'ready' || projStatus === 'rendered' || projStatus === 'awaiting_storyboard_review') {
completedCount++;
} else if (projStatus === 'error') {
failedCount++;
}
return {
...it,
status: projStatus,
projectTitle: proj?.title || it.title || it.prompt.slice(0, 60),
totalDurationSec: proj?.totalDurationSec || 0,
sceneCount: proj?.scenes?.length || 0,
renderOutputUrl,
};
});
const allDone = completedCount + failedCount >= items.length && items.length > 0;
const overallStatus = allDone
? failedCount === items.length
? 'failed'
: 'completed'
: r.status;
return {
id: r.id,
name: r.name,
status: overallStatus,
totalItems: items.length,
completedItems: completedCount,
failedItems: failedCount,
config,
items,
createdAt: r.created_at,
updatedAt: r.updated_at,
};
});
}
app.get('/api/batches', async () => {
return { batches: listEnrichedBatches() };
});
app.post('/api/batches', async (req, reply) => {
const body = (req.body as any) || {};
const rawItems = Array.isArray(body.items) ? body.items : [];
const validItems = rawItems
.map((it: any, idx: number) => ({
index: idx,
title: String(it.title || '').trim(),
prompt: String(it.prompt || '').trim(),
aspectRatio: it.aspectRatio || body.defaultAspectRatio || '9:16',
voiceId: it.voiceId || body.defaultVoiceId || 'Hải Đăng',
framePresetId:
it.framePresetId || body.defaultFramePresetId || 'editorial-clean-light',
projectId: '',
status: 'queued',
renderOutputUrl: '',
error: '',
}))
.filter((it: any) => it.prompt.length > 0);
if (validItems.length === 0) {
return reply
.code(400)
.send({ error: 'Vui lòng nhập ít nhất 1 dòng URL hoặc Prompt để chạy Batch.' });
}
const batchId = `bat-${crypto.randomUUID().slice(0, 8)}`;
const now = new Date().toISOString();
const batchName =
String(body.name || '').trim() ||
`Batch ${validItems.length} Video (${new Date().toLocaleDateString('vi-VN')})`;
const config = {
defaultAspectRatio: body.defaultAspectRatio || '9:16',
defaultVoiceId: body.defaultVoiceId || 'Hải Đăng',
defaultFramePresetId: body.defaultFramePresetId || 'editorial-clean-light',
brandKitId: body.brandKitId || '',
recipeId: body.recipeId || '',
creationMode: body.creationMode || 'auto',
autoRenderModal: Boolean(body.autoRenderModal),
};
db.prepare(`
INSERT INTO batch_jobs (
id, name, status, total_items, completed_items, failed_items,
config_json, items_json, created_at, updated_at
) VALUES (?, ?, 'running', ?, 0, 0, ?, ?, ?, ?)
`).run(
batchId,
batchName,
validItems.length,
JSON.stringify(config),
JSON.stringify(validItems),
now,
now
);
// Run sequential batch pipeline in background
void (async () => {
for (let i = 0; i < validItems.length; i++) {
const item = validItems[i];
try {
const proj = await startNewProjectPipeline({
title: item.title || undefined,
prompt: item.prompt,
aspectRatio: item.aspectRatio,
creationMode: config.creationMode,
framePresetId: item.framePresetId,
voiceId: item.voiceId,
brandKitId: config.brandKitId || undefined,
recipeId: config.recipeId || undefined,
});
validItems[i].projectId = proj.id;
validItems[i].title = proj.title;
validItems[i].status = proj.status;
db.prepare(
'UPDATE batch_jobs SET items_json = ?, updated_at = ? WHERE id = ?'
).run(JSON.stringify(validItems), new Date().toISOString(), batchId);
// Wait up to 90s for this item's pipeline to settle before starting next item
for (let tick = 0; tick < 45; tick++) {
await new Promise((r) => setTimeout(r, 2000));
const latest = getProjectById(proj.id);
if (!latest) break;
if (
['ready', 'awaiting_storyboard_review', 'rendered', 'error'].includes(
latest.status
)
) {
validItems[i].status = latest.status;
if (config.autoRenderModal && latest.status === 'ready') {
try {
await startProjectRenderJob(latest, 'modal', (upd) => {
if (upd.status === 'completed' && upd.outputUrl) {
const p = getProjectById(proj.id);
if (p) {
p.latestRenderUrl = upd.outputUrl;
p.renderOutputUrl = upd.outputUrl;
p.status = 'rendered';
saveProject(p);
}
}
});
} catch {}
}
break;
}
}
} catch (err: any) {
validItems[i].status = 'error';
validItems[i].error = err.message || 'Batch item failed';
}
db.prepare(
'UPDATE batch_jobs SET items_json = ?, updated_at = ? WHERE id = ?'
).run(JSON.stringify(validItems), new Date().toISOString(), batchId);
}
db.prepare(
"UPDATE batch_jobs SET status = 'completed', updated_at = ? WHERE id = ?"
).run(new Date().toISOString(), batchId);
})();
return {
success: true,
batchId,
batches: listEnrichedBatches(),
};
});
app.delete('/api/batches/:id', async (req) => {
const { id } = req.params as { id: string };
db.prepare('DELETE FROM batch_jobs WHERE id = ?').run(id);
return {
success: true,
batches: listEnrichedBatches(),
};
});
app.get('/api/projects/:id', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
return {
project,
versions: listProjectVersions(id),
};
});
app.delete('/api/projects/:id', async (req) => {
const { id } = req.params as { id: string };
deleteProjectById(id);
return { success: true, projects: listProjects() };
});
// Live SSE Progress Stream for Studio
app.get('/api/projects/:id/events', async (req, reply) => {
const { id } = req.params as { id: string };
reply.raw.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
const project = getProjectById(id);
if (project) {
reply.raw.write(
`data: ${JSON.stringify({
projectId: id,
stage: project.status,
progress: project.status === 'ready' ? 100 : 50,
message: `Trạng thái hiện tại: ${project.status}`,
status: project.status,
})}\n\n`
);
}
const unsubscribe = subscribeProjectProgress(id, (ev) => {
reply.raw.write(`data: ${JSON.stringify(ev)}\n\n`);
});
req.raw.on('close', () => {
unsubscribe();
});
});
app.post('/api/projects/:id/abort', async (req) => {
const { id } = req.params as { id: string };
abortProjectPipeline(id);
return { success: true, project: getProjectById(id) };
});
// Serve Live HyperFrames HTML Composition for iframe Preview
app.get('/api/projects/:id/preview', async (req, reply) => {
const { id } = req.params as { id: string };
const indexHtmlPath = path.join(PROJECTS_DIR, id, 'index.html');
if (!fs.existsSync(indexHtmlPath)) {
return reply
.type('text/html; charset=utf-8')
.send(
`<!DOCTYPE html><html><body style="background:#090d16;color:#94a3b8;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;"><div style="text-align:center;"><h3>Đang chuẩn bị bản dựng HyperFrames...</h3><p>Bản xem trước 60fps sẽ hiển thị ngay khi Frame Workers hoàn tất.</p></div></body></html>`
);
}
const html = fs.readFileSync(indexHtmlPath, 'utf8');
return reply.type('text/html; charset=utf-8').send(html);
});
app.get('/api/projects/:id/srt', async (req, reply) => {
const { id } = req.params as { id: string };
const srtPath = path.join(PROJECTS_DIR, id, 'subtitles.srt');
if (!fs.existsSync(srtPath)) {
return reply.code(404).send('Chưa có file phụ đề.');
}
return reply
.header('Content-Disposition', `attachment; filename="${id}-subtitles.srt"`)
.type('text/plain; charset=utf-8')
.send(fs.readFileSync(srtPath, 'utf8'));
});
// Update Storyboard scenes (titles, narrations, blueprintId, assigned assets, videoTrimStartSec)
app.put('/api/projects/:id/storyboard', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const {
scenes,
framePresetId,
voiceId,
voiceSpeed,
bgmTrackId,
rebuildComposition,
} = (req.body as any) || {};
if (framePresetId) project.framePresetId = framePresetId;
if (voiceId) project.voiceId = voiceId;
if (voiceSpeed) project.voiceSpeed = Number(voiceSpeed);
if (bgmTrackId) project.bgmTrackId = bgmTrackId;
if (Array.isArray(scenes)) {
let cursor = 0;
project.scenes = scenes.map((sc: any, idx: number) => {
const dur = Number(sc.durationSec || 4.5);
const start = Number(cursor.toFixed(2));
cursor += dur;
const words =
Array.isArray(sc.words) && sc.words.length > 0
? sc.words
: buildSyllableWeightedWordTimestamps(sc.narrationText || sc.title || '', dur);
return {
...project.scenes[idx],
...sc,
id: sc.id || `sc-${crypto.randomUUID().slice(0, 8)}`,
index: idx,
slug: sc.slug || `scene-${idx + 1}`,
startSec: start,
durationSec: dur,
words,
};
});
project.totalDurationSec = Number(cursor.toFixed(2));
}
saveProject(project);
if (rebuildComposition || project.status === 'ready' || project.status === 'rendered') {
const rebuilt = await buildAndValidateProjectScenes(project);
return { success: true, project: rebuilt };
}
return { success: true, project };
});
app.post('/api/projects/:id/scenes/:sceneIndex/regenerate-image', async (req, reply) => {
const { id, sceneIndex } = req.params as { id: string; sceneIndex: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const idx = parseInt(sceneIndex, 10);
const scene = project.scenes[idx];
if (!scene) return reply.code(404).send({ error: 'Không tìm thấy phân cảnh.' });
const body = (req.body as any) || {};
if (body.imagePrompt) scene.imagePrompt = body.imagePrompt;
const gen = await generateReferenceImageForScene({
projectId: project.id,
sceneIndex: idx,
sceneTitle: scene.title,
imagePrompt: scene.imagePrompt || scene.visualDirection,
aspectRatio: project.aspectRatio,
});
scene.assignedAssetIds = [gen.asset.id];
scene.referenceImageUrl = gen.imageUrl;
saveProject(project);
if (project.status === 'ready' || project.status === 'rendered') {
await buildAndValidateProjectScenes(project);
}
return { success: true, project, scene };
});
app.post('/api/projects/:id/scenes/:sceneIndex/resynthesize-voice', async (req, reply) => {
const { id, sceneIndex } = req.params as { id: string; sceneIndex: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const idx = parseInt(sceneIndex, 10);
const scene = project.scenes[idx];
if (!scene) return reply.code(404).send({ error: 'Không tìm thấy phân cảnh.' });
const body = (req.body as any) || {};
if (body.narrationText) scene.narrationText = body.narrationText;
const targetVoice = body.voiceId || project.voiceId;
const targetSpeed = Number(body.speed || project.voiceSpeed || 1.0);
if (body.voiceId) project.voiceId = body.voiceId;
const vo = await synthesizeSceneVoice({
projectId: project.id,
sceneIndex: idx,
text: scene.narrationText,
voiceId: targetVoice,
speed: targetSpeed,
});
scene.audioUrl = vo.audioUrl;
scene.audioDurationSec = vo.audioDurationSec;
scene.durationSec = vo.sceneDurationSec;
scene.words = vo.words;
let cursor = 0;
for (const s of project.scenes) {
s.startSec = Number(cursor.toFixed(2));
cursor += s.durationSec;
}
project.totalDurationSec = Number(cursor.toFixed(2));
saveProject(project);
if (project.status === 'ready' || project.status === 'rendered') {
await buildAndValidateProjectScenes(project);
}
return { success: true, project, scene };
});
// Approve Storyboard & Build HyperFrames Composition
app.post('/api/projects/:id/approve-storyboard', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const built = await buildAndValidateProjectScenes(project);
return { success: true, project: built };
});
// Surgical Prompt Edit
app.post('/api/projects/:id/prompt-edit', async (req, reply) => {
const { id } = req.params as { id: string };
const { editPrompt, targetSceneIndex } = (req.body as any) || {};
if (!editPrompt || !String(editPrompt).trim()) {
return reply.code(400).send({ error: 'Vui lòng nhập nội dung chỉnh sửa.' });
}
const res = await applySurgicalPromptEdit({
projectId: id,
editPrompt: String(editPrompt).trim(),
targetSceneIndex,
});
return {
success: true,
project: res.project,
summary: res.summary,
versions: listProjectVersions(id),
};
});
// 0-Second Direct Quick-Edit Inspector Save
app.post('/api/projects/:id/quick-edit', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const { sceneIndex, title, narrationText, referenceImageUrl, blueprintId } =
(req.body as any) || {};
const sc = project.scenes[Number(sceneIndex) || 0];
if (sc) {
if (typeof title === 'string') sc.title = title;
if (typeof narrationText === 'string') sc.narrationText = narrationText;
if (typeof referenceImageUrl === 'string') sc.referenceImageUrl = referenceImageUrl;
if (typeof blueprintId === 'string') sc.blueprintId = blueprintId;
}
const rebuilt = await buildAndValidateProjectScenes(project);
saveProjectVersionSnapshot(rebuilt, `Quick-Edit Cảnh #${(Number(sceneIndex) || 0) + 1}`);
return {
success: true,
project: rebuilt,
versions: listProjectVersions(id),
};
});
// 1-Click Aspect Ratio Remix (9:16 <-> 16:9 <-> 1:1)
app.post('/api/projects/:id/remix-aspect', async (req, reply) => {
const { id } = req.params as { id: string };
const { aspectRatio } = (req.body as any) || {};
const rebuilt = await remixProjectAspectRatio(id, aspectRatio || '16:9');
return {
success: true,
project: rebuilt,
versions: listProjectVersions(id),
};
});
// Restore Version (Undo / Redo)
app.post('/api/projects/:id/versions/:versionId/restore', async (req, reply) => {
const { id, versionId } = req.params as { id: string; versionId: string };
const restored = restoreProjectVersion(id, versionId);
if (!restored) return reply.code(404).send({ error: 'Không tìm thấy phiên bản.' });
return {
success: true,
project: restored,
versions: listProjectVersions(id),
};
});
// ==========================================================================
// 6. BRAND KITS, FROZEN RECIPES, RENDER JOBS & ADMIN VAULT ROUTES
// ==========================================================================
app.get('/api/brand-kits', async () => {
const rows = db
.prepare('SELECT data_json FROM brand_kits ORDER BY created_at DESC')
.all() as any[];
return { brandKits: rows.map((r) => JSON.parse(r.data_json)) };
});
app.post('/api/brand-kits', async (req) => {
const body = (req.body as any) || {};
const id = body.id || `brk-${crypto.randomUUID().slice(0, 8)}`;
const now = new Date().toISOString();
const kit = {
id,
name: body.name || 'Brand Kit mới',
brandName: body.brandName || body.name || 'My Brand',
logoUrl: body.logoUrl || '',
primaryColor: body.primaryColor || '#1e2bfa',
secondaryColor: body.secondaryColor || '#0f172a',
bgColor: body.bgColor || '#090d16',
headingFont: body.headingFont || 'Space Grotesk',
bodyFont: body.bodyFont || 'Be Vietnam Pro',
defaultVoiceId: body.defaultVoiceId || 'alloy',
defaultCtaText: body.defaultCtaText || 'Trải nghiệm ngay hôm nay!',
websiteUrl: body.websiteUrl || '',
createdAt: now,
};
db.prepare(
'INSERT OR REPLACE INTO brand_kits (id, name, data_json, created_at) VALUES (?, ?, ?, ?)'
).run(id, kit.name, JSON.stringify(kit), now);
return { success: true, brandKit: kit };
});
app.delete('/api/brand-kits/:id', async (req) => {
const { id } = req.params as { id: string };
db.prepare('DELETE FROM brand_kits WHERE id = ?').run(id);
return { success: true };
});
app.get('/api/recipes', async () => {
const rows = db
.prepare('SELECT data_json FROM frozen_recipes ORDER BY created_at DESC')
.all() as any[];
return { recipes: rows.map((r) => JSON.parse(r.data_json)) };
});
// Freeze an existing Project as a reusable Recipe Template!
app.post('/api/projects/:id/save-recipe', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const { name, description } = (req.body as any) || {};
const recipeId = `rcp-${crypto.randomUUID().slice(0, 8)}`;
const now = new Date().toISOString();
const recipe = {
id: recipeId,
name: name || `Mẫu từ: ${project.title}`,
description:
description ||
`Công thức ${project.scenes.length} cảnh (${project.aspectRatio}) đóng băng từ dự án "${project.title}"`,
framePresetId: project.framePresetId,
aspectRatio: project.aspectRatio,
sceneTemplates: project.scenes.map((s) => ({
role: s.role,
blueprintId: s.blueprintId,
motionRuleIds: s.motionRuleIds,
registryBlockName: s.registryBlockName,
durationSec: s.durationSec,
})),
createdAt: now,
};
db.prepare(
'INSERT INTO frozen_recipes (id, name, data_json, created_at) VALUES (?, ?, ?, ?)'
).run(recipeId, recipe.name, JSON.stringify(recipe), now);
return { success: true, recipe };
});
// Render Jobs (Modal Serverless + Local Fallback)
app.get('/api/renders', async (req) => {
const { projectId } = (req.query as { projectId?: string }) || {};
return { jobs: listRenderJobs(projectId) };
});
app.post('/api/projects/:id/render', async (req, reply) => {
const { id } = req.params as { id: string };
const project = getProjectById(id);
if (!project) return reply.code(404).send({ error: 'Không tìm thấy dự án.' });
const { provider } = (req.body as any) || {};
const job = await startProjectRenderJob(
project,
provider === 'local' ? 'local' : 'modal',
(updatedJob) => {
if (updatedJob.status === 'completed' && updatedJob.outputUrl) {
const p = getProjectById(id);
if (p) {
p.latestRenderUrl = updatedJob.outputUrl;
saveProject(p);
}
}
}
);
return { success: true, job };
});
app.post('/api/renders/:id/cancel', async (req) => {
const { id } = req.params as { id: string };
const job = cancelRenderJob(id);
return { success: true, job };
});
// Admin Overview, Usage Ledger & HF Vault Sync
app.get('/api/admin/overview', async () => {
const ledgerRows = db
.prepare('SELECT * FROM usage_ledger ORDER BY created_at DESC LIMIT 100')
.all() as any[];
const totals = db
.prepare(`
SELECT
COALESCE(SUM(prompt_tokens + completion_tokens), 0) as totalTokens,
COALESCE(SUM(tts_chars), 0) as totalTtsChars,
COALESCE(SUM(images_count), 0) as totalImages,
COALESCE(SUM(render_seconds), 0) as totalRenderSeconds
FROM usage_ledger
`)
.get() as any;
return {
totals,
recentUsage: ledgerRows,
vaultStatus: getVaultStatus(),
renders: listRenderJobs(),
};
});
app.post('/api/admin/vault/sync', async () => {
return await syncToHuggingFaceVault();
});
// Serve Frontend Dist if built
const webDistDir = path.resolve(process.cwd(), '../web/dist');
const rootWebDistDir = path.resolve(process.cwd(), 'apps/web/dist');
const activeDistDir = fs.existsSync(webDistDir)
? webDistDir
: fs.existsSync(rootWebDistDir)
? rootWebDistDir
: null;
if (activeDistDir) {
await app.register(fastifyStatic, {
root: activeDistDir,
prefix: '/',
decorateReply: false,
});
app.setNotFoundHandler((req, reply) => {
if (req.url.startsWith('/api/') || req.url.startsWith('/media/')) {
return reply.code(404).send({ error: 'Not Found' });
}
return reply
.type('text/html; charset=utf-8')
.send(fs.readFileSync(path.join(activeDistDir, 'index.html'), 'utf8'));
});
}
await app.listen({ port: PORT, host: HOST });
console.log(`🚀 OlokaFlow HyperFrames Server is running at http://localhost:${PORT}`);
}
bootstrapServer().catch((err) => {
console.error('Failed to start OlokaFlow server:', err);
process.exit(1);
});
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import Fastify from 'fastify';
import cors from '@fastify/cors';
import multipart from '@fastify/multipart';
import fastifyStatic from '@fastify/static';
import {
db,
DATA_DIR,
PROJECTS_DIR,
UPLOADS_DIR,
seedInitialDatabase,
} from './db/database.js';
import { hashPassword } from './db/crypto.js';
import {
getVaultStatus,
syncToHuggingFaceVault,
hydrateFromHuggingFaceVaultIfNeeded,
} from './db/vaultSync.js';
import {
listAIProfiles,
saveAIProfile,
deleteAIProfile,
duplicateAIProfile,
fetchModelsFromEndpoint,
testProfileConnection,
testModelPreflight,
testModelVision,
testVoiceOrMediaEndpoint,
getRoleRoutings,
saveRoleRoutings,
} from './services/aiProfileService.js';
import {
getFramePresets,
getSceneBlueprints,
getMotionRules,
getTransitions,
getRegistryCatalogItems,
searchHyperFramesCatalog,
} from './catalog/hyperframesKnowledgeBase.js';
import { VIETNAMESE_FONTS } from './services/fontService.js';
import {
AVAILABLE_VOICES,
listAvailableVoices,
listCustomClonedVoices,
createCustomClonedVoice,
deleteCustomClonedVoice,
synthesizeSceneVoice,
buildSyllableWeightedWordTimestamps,
} from './services/voiceService.js';
import { BGM_CATALOG, SFX_CATALOG } from './services/audioMixService.js';
import { generateReferenceImageForScene } from './services/imageGenService.js';
import {
inspectBinaryMagicBytes,
scrapeWebpageUrl,
searchWebFallbackImages,
} from './services/promptAssetScraperService.js';
import {
listAssets,
getAssetById,
saveAndAnalyzeAsset,
deleteAssetById,
} from './services/assetSearchService.js';
import {
listProjects,
getProjectById,
saveProject,
deleteProjectById,
startNewProjectPipeline,
buildAndValidateProjectScenes,
applySurgicalPromptEdit,
remixProjectAspectRatio,
abortProjectPipeline,
subscribeProjectProgress,
listProjectVersions,
restoreProjectVersion,
saveProjectVersionSnapshot,
} from './agent/orchestrator.js';
import {
listRenderJobs,
startProjectRenderJob,
cancelRenderJob,
} from './services/modalRenderService.js';
const PORT = Number(process.env.PORT || 7860);
const HOST = process.env.HOST || '0.0.0.0';
async function bootstrapServer() {
seedInitialDatabase();
await hydrateFromHuggingFaceVaultIfNeeded();
// Ensure every existing project has its compiled HyperFrames index.html on disk
for (const proj of listProjects()) {
const htmlPath = path.join(PROJECTS_DIR, proj.id, 'index.html');
if (!fs.existsSync(htmlPath) && proj.scenes && proj.scenes.length > 0) {
try {
await buildAndValidateProjectScenes(proj);
} catch (err: any) {