feat(enterprise): add Batch URL/CSV Video Factory, Zero-Shot Voice Cloning Studio & Auth Login Gate
Browse filesFiles changed (7)
182 unmodified lines183184185186187188182 unmodified linesvalue_json TEXT NOT NULL,updated_at TEXT NOT NULL);`);export function seedInitialDatabase(): void {182 unmodified lines183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215182 unmodified linesvalue_json TEXT NOT NULL,updated_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS custom_voices (id TEXT PRIMARY KEY,name TEXT NOT NULL,voice_id TEXT NOT NULL,gender TEXT NOT NULL DEFAULT 'Nam',region TEXT NOT NULL DEFAULT 'Việt Nam',description TEXT NOT NULL DEFAULT '',ref_text TEXT NOT NULL DEFAULT '',sample_audio_path TEXT NOT NULL DEFAULT '',sample_public_url TEXT NOT NULL DEFAULT '',fallback_voice_id TEXT NOT NULL DEFAULT 'Hải Đăng',created_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS batch_jobs (id TEXT PRIMARY KEY,name TEXT NOT NULL,status TEXT NOT NULL DEFAULT 'running',total_items INTEGER NOT NULL DEFAULT 0,completed_items INTEGER NOT NULL DEFAULT 0,failed_items INTEGER NOT NULL DEFAULT 0,config_json TEXT NOT NULL DEFAULT '{}',items_json TEXT NOT NULL DEFAULT '[]',created_at TEXT NOT NULL,updated_at TEXT NOT NULL);`);export function seedInitialDatabase(): void {
43 unmodified lines44454647484962 unmodified lines11211311411511611711811929 unmodified lines1491501511521531546 unmodified lines1611621631641651661671681691701711721731741751763 unmodified lines180181182183184185110 unmodified lines296297298299300301302180 unmodified lines48348448548648748843 unmodified linesimport {AVAILABLE_VOICES,listAvailableVoices,synthesizeSceneVoice,buildSyllableWeightedWordTimestamps,} from './services/voiceService.js';62 unmodified lines});// ==========================================================================// 1. AUTH & USER MANAGEMENT ROUTES// ==========================================================================app.post('/api/auth/login', async (req, reply) => {const { email, password } = (req.body as any) || {};const user = db29 unmodified lines).all() as any[];return {users: rows.map((u) => ({id: u.id,email: u.email,6 unmodified lines};});app.post('/api/admin/users', async (req) => {const body = (req.body as any) || {};const id = `usr-${crypto.randomUUID().slice(0, 8)}`;const now = new Date().toISOString();db.prepare(`INSERT INTO users (id, email, name, role, password_hash, token_quota, tokens_used, created_at)VALUES (?, ?, ?, ?, ?, ?, 0, ?)`).run(id,body.email,body.name || 'Creator',body.role || 'creator',hashPassword(body.password || 'oloka123'),3 unmodified linesreturn { success: true, id };});// ==========================================================================// 2. MULTI-PROFILE AI HUB & 4-TIER LIVE CONNECTION TESTER ROUTES// ==========================================================================110 unmodified linesapp.get('/api/voices', async () => {const voices = await listAvailableVoices();return { voices };});const getCatalogPayload = async () => {180 unmodified linesreturn { success: true, project };});app.get('/api/projects/:id', async (req, reply) => {const { id } = req.params as { id: string };const project = getProjectById(id);43 unmodified lines44454647484950515262 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020129 unmodified lines2312322332342352362376 unmodified lines2442452462472482492502512522532542552562572582592602612623 unmodified lines266267268269270271272273274275276277278279280110 unmodified lines391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457180 unmodified lines63863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084143 unmodified linesimport {AVAILABLE_VOICES,listAvailableVoices,listCustomClonedVoices,createCustomClonedVoice,deleteCustomClonedVoice,synthesizeSceneVoice,buildSyllableWeightedWordTimestamps,} from './services/voiceService.js';62 unmodified lines});// ==========================================================================// 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 = db29 unmodified lines).all() as any[];return {requireAuthGate: getRequireAuthGate(),users: rows.map((u) => ({id: u.id,email: u.email,6 unmodified lines};});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'),3 unmodified linesreturn { 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// ==========================================================================110 unmodified linesapp.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 () => {180 unmodified linesreturn { 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 backgroundvoid (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 itemfor (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);
2 unmodified lines34567898 unmodified lines181920212223242526112 unmodified lines13914014114214314414514614714814915015133 unmodified lines185186187188189190191192193194195196197198112 unmodified lines31131231331431531631731831932032132232332432532638 unmodified lines3653663673683693703713723733743753761 unmodified line3783793803813823832 unmodified linesimport crypto from 'node:crypto';import { execFile } from 'node:child_process';import { promisify } from 'node:util';import { AUDIO_CACHE_DIR, logUsage } from '../db/database.js';import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js';import { probeMediaDurationSec } from './assetAnalysisService.js';import type { WordTimestamp } from '@olokaflow/shared';8 unmodified linesregion: string;description: string;lang: string;provider: 'olokatts' | 'openai';isEditorsPick?: boolean;previewUrl?: string;}export interface SynthesizedSceneVoice {112 unmodified lineslet cachedLiveVoices: VoiceCatalogItem[] | null = null;let cachedVoicesTimestamp = 0;/*** Fetches the live 25 Vietnamese voices from https://tts.oloka.net/v1/voices* and merges with OpenAI standard voices.*/export async function listAvailableVoices(): Promise<VoiceCatalogItem[]> {if (cachedLiveVoices && Date.now() - cachedVoicesTimestamp < 5 * 60 * 1000) {return cachedLiveVoices;}try {33 unmodified linesconst openaiExtras = STATIC_FALLBACK_VOICES.filter((v) => v.provider === 'openai');cachedLiveVoices = [...olokaVoices, ...openaiExtras];cachedVoicesTimestamp = Date.now();return cachedLiveVoices;}}} catch (err: any) {console.warn(`[VoiceService] Live OlokaTTS catalog fetch note: ${err.message}`);}return STATIC_FALLBACK_VOICES;}export const AVAILABLE_VOICES = STATIC_FALLBACK_VOICES;112 unmodified linesconst cleanText = normalizeVietnameseTtsText(params.text || '');const speed = Math.max(0.5, Math.min(2.0, Number(params.speed || 1.0)));// Resolve voiceId against live catalog if an id like 'vp_haidang' was passedconst catalog = await listAvailableVoices();const matchedVoice = catalog.find((v) => v.id === params.voiceId || v.voiceId === params.voiceId);const resolvedVoiceName = matchedVoice ? matchedVoice.voiceId : params.voiceId || 'Hải Đăng';const hash = crypto.createHash('sha256').update(`${resolvedVoiceName}:${speed}:${cleanText}`).digest('hex').slice(0, 16);38 unmodified linesconst startTime = Date.now();try {const requestBody = isOlokaTts? {model: modelId || 'olokatts-v3-turbo',voice: resolvedVoiceName,input: cleanText,speed,}: {model: modelId || 'tts-1-hd',1 unmodified lineinput: cleanText,speed,response_format: 'mp3',};const resp = await fetch(speechEndpoint, {2 unmodified lines34567898 unmodified lines181920212223242526272829112 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422533 unmodified lines259260261262263264265266267268269270271272112 unmodified lines38538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741838 unmodified lines4574584594604614624634644654664674684694704714724734741 unmodified line4764774784794804814824834844854864872 unmodified linesimport crypto from 'node:crypto';import { execFile } from 'node:child_process';import { promisify } from 'node:util';import { db, AUDIO_CACHE_DIR, logUsage } from '../db/database.js';import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js';import { probeMediaDurationSec } from './assetAnalysisService.js';import type { WordTimestamp } from '@olokaflow/shared';8 unmodified linesregion: string;description: string;lang: string;provider: 'olokatts' | 'openai' | 'cloned';isEditorsPick?: boolean;previewUrl?: string;refText?: string;sampleAudioPath?: string;fallbackVoiceId?: string;}export interface SynthesizedSceneVoice {112 unmodified lineslet cachedLiveVoices: VoiceCatalogItem[] | null = null;let cachedVoicesTimestamp = 0;export function listCustomClonedVoices(): VoiceCatalogItem[] {try {const rows = db.prepare('SELECT * FROM custom_voices ORDER BY created_at DESC').all() as any[];return rows.map((r) => ({id: r.id,name: `${r.name} (Clone • ${r.gender})`,voiceId: r.voice_id || r.id,gender: r.gender || 'Nam',region: r.region || 'Việt Nam',description:r.description || 'Giọng đọc Clone cá nhân hóa (Zero-Shot Voice Clone)',lang: 'Tiếng Việt',provider: 'cloned' as const,isEditorsPick: true,previewUrl: r.sample_public_url || '',refText: r.ref_text || '',sampleAudioPath: r.sample_audio_path || '',fallbackVoiceId: r.fallback_voice_id || 'Hải Đăng',}));} catch {return [];}}export function createCustomClonedVoice(params: {name: string;gender: string;region: string;description?: string;refText?: string;sampleAudioPath: string;samplePublicUrl: string;fallbackVoiceId?: string;}): VoiceCatalogItem {const id = `vc-clone-${crypto.randomUUID().slice(0, 8)}`;const now = new Date().toISOString();const cleanName = params.name.trim() || 'Giọng Clone Mới';const fallbackVoice =params.fallbackVoiceId || (params.gender === 'Nữ' ? 'Trúc Ly' : 'Hải Đăng');db.prepare(`INSERT INTO custom_voices (id, name, voice_id, gender, region, description, ref_text,sample_audio_path, sample_public_url, fallback_voice_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id,cleanName,id,params.gender || 'Nam',params.region || 'Việt Nam',params.description || 'Giọng đọc Clone cá nhân hóa từ file mẫu',params.refText || '',params.sampleAudioPath,params.samplePublicUrl,fallbackVoice,now);cachedLiveVoices = null;return listCustomClonedVoices().find((v) => v.id === id)!;}export function deleteCustomClonedVoice(id: string): void {db.prepare('DELETE FROM custom_voices WHERE id = ?').run(id);cachedLiveVoices = null;}/*** Fetches the live 25 Vietnamese voices from https://tts.oloka.net/v1/voices* and merges with custom cloned voices + OpenAI standard voices.*/export async function listAvailableVoices(): Promise<VoiceCatalogItem[]> {const customClones = listCustomClonedVoices();if (cachedLiveVoices && Date.now() - cachedVoicesTimestamp < 5 * 60 * 1000) {return [...customClones, ...cachedLiveVoices];}try {33 unmodified linesconst openaiExtras = STATIC_FALLBACK_VOICES.filter((v) => v.provider === 'openai');cachedLiveVoices = [...olokaVoices, ...openaiExtras];cachedVoicesTimestamp = Date.now();return [...customClones, ...cachedLiveVoices];}}} catch (err: any) {console.warn(`[VoiceService] Live OlokaTTS catalog fetch note: ${err.message}`);}return [...customClones, ...STATIC_FALLBACK_VOICES];}export const AVAILABLE_VOICES = STATIC_FALLBACK_VOICES;112 unmodified linesconst cleanText = normalizeVietnameseTtsText(params.text || '');const speed = Math.max(0.5, Math.min(2.0, Number(params.speed || 1.0)));// Resolve voiceId against live catalog if an id like 'vp_haidang' or a cloned voice was passedconst catalog = await listAvailableVoices();const matchedVoice = catalog.find((v) => v.id === params.voiceId || v.voiceId === params.voiceId);const isClonedVoice = matchedVoice?.provider === 'cloned';const resolvedVoiceName = isClonedVoice? matchedVoice.fallbackVoiceId || 'Hải Đăng': matchedVoice? matchedVoice.voiceId: params.voiceId || 'Hải Đăng';let clonedAudioB64 = '';if (isClonedVoice &&matchedVoice?.sampleAudioPath &&fs.existsSync(matchedVoice.sampleAudioPath)) {try {clonedAudioB64 = fs.readFileSync(matchedVoice.sampleAudioPath).toString('base64');} catch {}}const hash = crypto.createHash('sha256').update(`${matchedVoice?.id || resolvedVoiceName}:${speed}:${cleanText}`).digest('hex').slice(0, 16);38 unmodified linesconst startTime = Date.now();try {const requestBody: Record<string, any> = isOlokaTts? {model: modelId || 'olokatts-v3-turbo',voice: resolvedVoiceName,input: cleanText,speed,...(clonedAudioB64? {reference_audio_b64: clonedAudioB64,ref_text: matchedVoice?.refText || undefined,}: {}),}: {model: modelId || 'tts-1-hd',1 unmodified lineinput: cleanText,speed,response_format: 'mp3',...(clonedAudioB64? {reference_audio_b64: clonedAudioB64,ref_text: matchedVoice?.refText || undefined,}: {}),};const resp = await fetch(speechEndpoint, {
11 unmodified lines1213141516171819205 unmodified lines2627282930311 unmodified line33343536373814 unmodified lines5354555657586 unmodified lines65666768697071727374757677786 unmodified lines858687888990919212 unmodified lines10510610710810911011111211323 unmodified lines13713813914014114214314412 unmodified lines15715815916016116216316416516616716816963 unmodified lines23323423523623723823925 unmodified lines2652662672682692702712722732 unmodified lines27627727827928028128228328415 unmodified lines3003013023033043053063071 unmodified line309310311312313314315113 unmodified lines42943043143243343443517 unmodified lines4534544554564574584594 unmodified lines4644654664674684694704714724734744754764774784794803 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850965 unmodified lines57557657757857958011 unmodified linesRefreshCw,Sparkles,Plus,Clock,ShieldCheck,Activity,} from 'lucide-react';import { api } from './api';import type {5 unmodified linesFrozenRecipe,} from '@olokaflow/shared';import { StudioWorkspaceView } from './components/StudioWorkspaceView';import { AIProfileHubView } from './components/AIProfileHubView';import { AssetLibraryView } from './components/AssetLibraryView';import { CatalogBrowserView } from './components/CatalogBrowserView';1 unmodified linetype MainTab =| 'studio'| 'voices'| 'assets'| 'catalog'14 unmodified linesconst [vaultStatus, setVaultStatus] = useState<any>(null);const [syncingVault, setSyncingVault] = useState(false);// Brand Kit quick form stateconst [newBrandName, setNewBrandName] = useState('');const [newBrandTagline, setNewBrandTagline] = useState('');6 unmodified linesasync function loadAllState() {try {const [projRes, catRes, aiRes, astRes, brdRes, vltRes] = await Promise.all([api.getProjects(),api.getCatalog(),api.getAIProfiles(),api.getAssets(),api.getBrandsAndRecipes(),api.getVaultStatus(),]);const pList = projRes.projects || [];setProjects(pList);if (!activeProjectId && pList.length > 0) {6 unmodified linessetBrands(brdRes.brands || []);setRecipes(brdRes.recipes || []);setVaultStatus(vltRes);} catch (err) {console.error('Load state error:', err);}}12 unmodified linesicon: Film,badge: projects.length,},{id: 'voices',label: 'Giọng Đọc OlokaTTS',icon: Mic,badge: catalog?.voices?.length || 25,},23 unmodified lines},{id: 'vault',label: 'HF Cloud Vault & Dự Án',icon: Cloud,},];12 unmodified linesawait loadAllState();}return (<div className="min-h-screen flex bg-[#FAF9F6] text-zinc-900">{/* =====================================================================LEFT EDITORIAL NAVIGATION RAIL (DESIGN.MD + TASTE-DESIGN + SHADCN)===================================================================== */}<aside className="w-64 shrink-0 bg-white border-r border-zinc-200/90 flex flex-col justify-between sticky top-0 h-screen z-30"><div className="p-4 space-y-5">{/* Brand Logo Lockup */}<div className="flex items-center gap-3 px-2 pt-1"><div className="w-9 h-9 rounded-xl bg-[#E11D48] text-white flex items-center justify-center shadow-xs">63 unmodified lines{projects.length}</span></div><div className="space-y-1 max-h-56 overflow-y-auto pr-1">{projects.map((p) => {const isSel =activeProject?.id === p.id && activeTab === 'studio';25 unmodified lines</div></div>{/* Bottom System Telemetry Card */}<div className="p-4 border-t border-zinc-200/80 bg-zinc-50/60 space-y-2"><div className="flex items-center justify-between text-[11px]"><span className="font-semibold text-zinc-600 flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-emerald-500" />OlokaTTS + Modal2 unmodified lines60 FPS</span></div><div className="text-[10px] text-zinc-400 leading-relaxed font-mono truncate">Vault: {vaultStatus?.vaultRepo || 'phucsd/olokaflow-vault'}</div></div></aside>15 unmodified lines/>)}{activeTab === 'voices' && (<CatalogBrowserView catalog={catalog} initialSubTab="voices" />)}{activeTab === 'assets' && (1 unmodified line)}{activeTab === 'catalog' && (<CatalogBrowserView catalog={catalog} initialSubTab="blueprints" />)}{activeTab === 'ai_profiles' && (113 unmodified lines{b.tagline || b.defaultCtaText}</p><div className="text-[11px] font-mono text-zinc-400">Voice: {b.defaultVoiceId} • Font: {b.headingFont || 'Plus Jakarta Sans'}</div></div>))}17 unmodified lines{r.description}</p><div className="text-[10px] font-mono tabular-nums text-[#E11D48] font-semibold">Preset: {r.framePresetId} • {r.defaultAspectRatio || r.aspectRatio}</div></div>))}4 unmodified lines</div>)}{/* HF CLOUD VAULT & PROJECT MANAGEMENT TAB */}{activeTab === 'vault' && (<div className="space-y-6"><div className="fliki-card p-6 bg-white flex flex-wrap items-center justify-between gap-4"><div><Badge variant="emerald" className="mb-1.5"><ShieldCheck className="w-3 h-3" />Hugging Face Private Dataset Vault + AES-256-GCM</Badge><h2 className="text-xl font-bold tracking-tight text-zinc-900">Đồng Bộ Lưu Trữ Đám Mây Vĩnh Viễn & Quản Trị Dự Án Video</h2><p className="text-xs text-zinc-500 mt-0.5">Tự động sao lưu SQLite WAL, cấu hình AI đã mã hóa và toàn bộ dự án HyperFrames lên Private Dataset{' '}3 unmodified lines.</p></div><Buttonvariant="primary"disabled={syncingVault}onClick={async () => {setSyncingVault(true);try {const res = await api.triggerVaultBackup();setVaultStatus(res);} finally {setSyncingVault(false);}}}><RefreshCwclassName={`w-3.5 h-3.5 ${syncingVault ? 'animate-spin' : ''}`}/>{syncingVault? 'Đang đồng bộ lên HF Vault...': 'Sao Lưu Ngay Lên HF Private Dataset'}</Button></div><div className="fliki-card p-6 bg-white space-y-4">65 unmodified lines</div>)}</main></div>);};11 unmodified lines121314151617181920212223245 unmodified lines303132333435361 unmodified line3839404142434414 unmodified lines59606162636465666768697071727374757677787980816 unmodified lines8889909192939495969798991001011021031041051061071081091101111121136 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617712 unmodified lines19019119219319419519619719819920020120220320423 unmodified lines22822923023123223323423523612 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533663 unmodified lines40040140240340440540625 unmodified lines4324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984992 unmodified lines50250350450550650715 unmodified lines5235245255265275285295305315325335345355365375385395405415425435445455465471 unmodified line549550551552553554555556557558559113 unmodified lines67367467567667767867968017 unmodified lines6986997007017027037047054 unmodified lines7107117127137147157167177187197207217227237247257263 unmodified lines73073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991065 unmodified lines9769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104311 unmodified linesRefreshCw,Sparkles,Plus,ShieldCheck,Lock,Unlock,Users,LogOut,LogIn,FileSpreadsheet,} from 'lucide-react';import { api } from './api';import type {5 unmodified linesFrozenRecipe,} from '@olokaflow/shared';import { StudioWorkspaceView } from './components/StudioWorkspaceView';import { BatchStudioView } from './components/BatchStudioView';import { AIProfileHubView } from './components/AIProfileHubView';import { AssetLibraryView } from './components/AssetLibraryView';import { CatalogBrowserView } from './components/CatalogBrowserView';1 unmodified linetype MainTab =| 'studio'| 'batch'| 'voices'| 'assets'| 'catalog'14 unmodified linesconst [vaultStatus, setVaultStatus] = useState<any>(null);const [syncingVault, setSyncingVault] = useState(false);// Auth Login Gate & Team Governance Stateconst [authChecked, setAuthChecked] = useState(false);const [requireAuthGate, setRequireAuthGate] = useState(false);const [currentUser, setCurrentUser] = useState<any | null>(null);const [showLoginModal, setShowLoginModal] = useState(false);const [loginEmail, setLoginEmail] = useState('admin@olokaflow.ai');const [loginPassword, setLoginPassword] = useState('admin123');const [loginError, setLoginError] = useState('');const [loginBusy, setLoginBusy] = useState(false);const [teamUsers, setTeamUsers] = useState<any[]>([]);const [newUserEmail, setNewUserEmail] = useState('');const [newUserName, setNewUserName] = useState('');const [newUserPassword, setNewUserPassword] = useState('');const [newUserRole, setNewUserRole] = useState<'creator' | 'admin'>('creator');const [newUserQuota, setNewUserQuota] = useState(5000000);// Brand Kit quick form stateconst [newBrandName, setNewBrandName] = useState('');const [newBrandTagline, setNewBrandTagline] = useState('');6 unmodified linesasync function loadAllState() {try {const [authRes, projRes, catRes, aiRes, astRes, brdRes, vltRes, usrRes] =await Promise.all([api.getAuthMe().catch(() => ({authenticated: false,requireAuthGate: false,user: null,})),api.getProjects(),api.getCatalog(),api.getAIProfiles(),api.getAssets(),api.getBrandsAndRecipes(),api.getVaultStatus(),api.getUsers().catch(() => ({ users: [] })),]);setRequireAuthGate(Boolean(authRes.requireAuthGate));setCurrentUser(authRes.user || null);setAuthChecked(true);const pList = projRes.projects || [];setProjects(pList);if (!activeProjectId && pList.length > 0) {6 unmodified linessetBrands(brdRes.brands || []);setRecipes(brdRes.recipes || []);setVaultStatus(vltRes);setTeamUsers(usrRes.users || []);} catch (err) {console.error('Load state error:', err);setAuthChecked(true);}}async function handleLoginSubmit(e: React.FormEvent) {e.preventDefault();setLoginBusy(true);setLoginError('');try {const res = await api.login(loginEmail.trim(), loginPassword);setCurrentUser(res.user);setShowLoginModal(false);await loadAllState();} catch (err: any) {setLoginError(err.message || 'Đăng nhập thất bại');} finally {setLoginBusy(false);}}async function handleToggleAuthGate(nextVal: boolean) {try {const res = await api.setAuthGate(nextVal);setRequireAuthGate(res.requireAuthGate);if (nextVal && !currentUser) {setShowLoginModal(true);}} catch (err: any) {alert(`Lỗi cập nhật Auth Gate: ${err.message}`);}}async function handleCreateTeamUser(e: React.FormEvent) {e.preventDefault();if (!newUserEmail.trim()) return;try {await api.createUser({email: newUserEmail.trim(),name: newUserName.trim() || 'Creator',password: newUserPassword || 'oloka123',role: newUserRole,tokenQuota: Number(newUserQuota) || 5000000,});setNewUserEmail('');setNewUserName('');setNewUserPassword('');await loadAllState();} catch (err: any) {alert(`Lỗi tạo tài khoản: ${err.message}`);}}12 unmodified linesicon: Film,badge: projects.length,},{id: 'batch',label: 'Sản Xuất Hàng Loạt',icon: FileSpreadsheet,badge: 'Batch',},{id: 'voices',label: 'Giọng Đọc & Clone',icon: Mic,badge: catalog?.voices?.length || 25,},23 unmodified lines},{id: 'vault',label: 'HF Vault & Quản Trị Team',icon: Cloud,badge: teamUsers.length,},];12 unmodified linesawait loadAllState();}// Full-Screen Login Gate when requireAuthGate is enabled and user is not logged inif (authChecked && requireAuthGate && !currentUser) {return (<div className="min-h-screen bg-[#FAF9F6] flex items-center justify-center p-4"><formonSubmit={handleLoginSubmit}className="fliki-card p-7 bg-white max-w-md w-full space-y-5 shadow-lg"><div className="flex items-center gap-3"><div className="w-10 h-10 rounded-xl bg-[#E11D48] text-white flex items-center justify-center shadow-xs"><Film className="w-5 h-5 stroke-[2.2]" /></div><div><div className="flex items-center gap-1.5"><span className="font-extrabold text-lg tracking-tight text-zinc-900">OlokaFlow Studio</span><Badge variant="crimson" mono>AUTH GATE</Badge></div><p className="text-xs text-zinc-500">Đăng nhập để truy cập hệ thống tạo video HyperFrames 60fps</p></div></div>{loginError && (<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs font-semibold text-[#E11D48]">{loginError}</div>)}<div className="space-y-3"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Email đăng nhập</label><inputtype="email"value={loginEmail}onChange={(e) => setLoginEmail(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2.5 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"required/></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Mật khẩu</label><inputtype="password"value={loginPassword}onChange={(e) => setLoginPassword(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2.5 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"required/></div></div><Buttontype="submit"variant="primary"size="lg"className="w-full"disabled={loginBusy}><LogIn className="w-4 h-4" /><span>{loginBusy ? 'Đang xác thực...' : 'Đăng Nhập Vào Studio'}</span></Button></form></div>);}return (<div className="min-h-screen flex bg-[#FAF9F6] text-zinc-900">{/* =====================================================================LEFT EDITORIAL NAVIGATION RAIL (DESIGN.MD + TASTE-DESIGN + SHADCN)===================================================================== */}<aside className="w-64 shrink-0 bg-white border-r border-zinc-200/90 flex flex-col justify-between sticky top-0 h-screen z-30"><div className="p-4 space-y-5 overflow-y-auto">{/* Brand Logo Lockup */}<div className="flex items-center gap-3 px-2 pt-1"><div className="w-9 h-9 rounded-xl bg-[#E11D48] text-white flex items-center justify-center shadow-xs">63 unmodified lines{projects.length}</span></div><div className="space-y-1 max-h-48 overflow-y-auto pr-1">{projects.map((p) => {const isSel =activeProject?.id === p.id && activeTab === 'studio';25 unmodified lines</div></div>{/* Bottom Auth & System Telemetry Card */}<div className="p-3.5 border-t border-zinc-200/80 bg-zinc-50/70 space-y-2.5"><div className="flex items-center justify-between">{currentUser ? (<div className="flex items-center justify-between w-full gap-2"><div className="min-w-0"><div className="text-xs font-bold text-zinc-900 truncate">{currentUser.name}</div><div className="text-[10px] font-mono text-zinc-500 truncate">{currentUser.role.toUpperCase()} • {currentUser.email}</div></div><buttontype="button"onClick={async () => {await api.logout();setCurrentUser(null);}}className="p-1.5 rounded-lg hover:bg-zinc-200 text-zinc-500 hover:text-zinc-900 cursor-pointer"title="Đăng xuất"><LogOut className="w-3.5 h-3.5" /></button></div>) : (<div className="flex items-center justify-between w-full gap-2"><buttontype="button"onClick={() => setShowLoginModal(true)}className="text-xs font-semibold text-zinc-700 hover:text-[#E11D48] flex items-center gap-1.5 cursor-pointer"><LogIn className="w-3.5 h-3.5 text-[#E11D48]" /><span>Đăng nhập Admin</span></button><buttontype="button"onClick={() => handleToggleAuthGate(!requireAuthGate)}className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-semibold flex items-center gap-1 cursor-pointer ${requireAuthGate? 'bg-rose-100 text-[#E11D48]': 'bg-zinc-200/80 text-zinc-600'}`}title="Bật/Tắt cổng đăng nhập bắt buộc cho toàn trang">{requireAuthGate ? (<><Lock className="w-2.5 h-2.5" /><span>LOCKED</span></>) : (<><Unlock className="w-2.5 h-2.5" /><span>OPEN</span></>)}</button></div>)}</div><div className="flex items-center justify-between text-[11px] pt-1 border-t border-zinc-200/60"><span className="font-semibold text-zinc-600 flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-emerald-500" />OlokaTTS + Modal2 unmodified lines60 FPS</span></div></div></aside>15 unmodified lines/>)}{activeTab === 'batch' && (<BatchStudioViewcatalog={catalog}brands={brands}recipes={recipes}onOpenProjectInStudio={(id) => {setActiveProjectId(id);setActiveTab('studio');}}onRefreshAll={loadAllState}/>)}{activeTab === 'voices' && (<CatalogBrowserViewcatalog={catalog}initialSubTab="voices"onRefreshCatalog={loadAllState}/>)}{activeTab === 'assets' && (1 unmodified line)}{activeTab === 'catalog' && (<CatalogBrowserViewcatalog={catalog}initialSubTab="blueprints"onRefreshCatalog={loadAllState}/>)}{activeTab === 'ai_profiles' && (113 unmodified lines{b.tagline || b.defaultCtaText}</p><div className="text-[11px] font-mono text-zinc-400">Voice: {b.defaultVoiceId} • Font:{' '}{b.headingFont || 'Plus Jakarta Sans'}</div></div>))}17 unmodified lines{r.description}</p><div className="text-[10px] font-mono tabular-nums text-[#E11D48] font-semibold">Preset: {r.framePresetId} •{' '}{r.defaultAspectRatio || r.aspectRatio}</div></div>))}4 unmodified lines</div>)}{/* HF CLOUD VAULT, TEAM GOVERNANCE & PROJECT MANAGEMENT TAB */}{activeTab === 'vault' && (<div className="space-y-6"><div className="fliki-card p-6 bg-white flex flex-wrap items-center justify-between gap-4"><div><Badge variant="emerald" className="mb-1.5"><ShieldCheck className="w-3 h-3" />Hugging Face Private Dataset Vault + Team Auth Gate</Badge><h2 className="text-xl font-bold tracking-tight text-zinc-900">Đồng Bộ Lưu Trữ Đám Mây Vĩnh Viễn, Bảo Mật Đăng Nhập & Quản Trị Team</h2><p className="text-xs text-zinc-500 mt-0.5">Tự động sao lưu SQLite WAL, cấu hình AI đã mã hóa và toàn bộ dự án HyperFrames lên Private Dataset{' '}3 unmodified lines.</p></div><div className="flex items-center gap-2 flex-wrap"><Buttonvariant={requireAuthGate ? 'outlineCrimson' : 'secondary'}onClick={() => handleToggleAuthGate(!requireAuthGate)}>{requireAuthGate ? (<><Lock className="w-3.5 h-3.5" /><span>Cổng Đăng Nhập: ĐANG BẬT (Bấm để Mở)</span></>) : (<><Unlock className="w-3.5 h-3.5" /><span>Cổng Đăng Nhập: ĐANG MỞ (Bấm để Khóa)</span></>)}</Button><Buttonvariant="primary"disabled={syncingVault}onClick={async () => {setSyncingVault(true);try {const res = await api.triggerVaultBackup();setVaultStatus(res);} finally {setSyncingVault(false);}}}><RefreshCwclassName={`w-3.5 h-3.5 ${syncingVault ? 'animate-spin' : ''}`}/>{syncingVault? 'Đang đồng bộ lên HF Vault...': 'Sao Lưu Ngay Lên HF Private Dataset'}</Button></div></div>{/* Team Governance Grid */}<div className="grid grid-cols-1 lg:grid-cols-12 gap-5"><formonSubmit={handleCreateTeamUser}className="lg:col-span-5 fliki-card p-5 bg-white space-y-3.5"><h3 className="text-sm font-bold text-zinc-900 flex items-center gap-2"><Users className="w-4 h-4 text-[#E11D48]" /><span>Cấp Tài Khoản Thành Viên Mới (Team Member)</span></h3><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Email đăng nhập *</label><inputtype="email"value={newUserEmail}onChange={(e) => setNewUserEmail(e.target.value)}placeholder="editor@olokaflow.ai"className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900"required/></div><div className="grid grid-cols-2 gap-2.5"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Tên hiển thị</label><inputtype="text"value={newUserName}onChange={(e) => setNewUserName(e.target.value)}placeholder="Video Editor"className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs text-zinc-900"/></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Mật khẩu khởi tạo</label><inputtype="text"value={newUserPassword}onChange={(e) => setNewUserPassword(e.target.value)}placeholder="oloka123"className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-mono text-zinc-900"/></div></div><div className="grid grid-cols-2 gap-2.5"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Phân quyền (Role)</label><selectvalue={newUserRole}onChange={(e) =>setNewUserRole(e.target.value as 'creator' | 'admin')}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"><option value="creator">Creator (Biên tập Video)</option><option value="admin">Admin (Toàn quyền)</option></select></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Hạn mức Token</label><inputtype="number"value={newUserQuota}onChange={(e) => setNewUserQuota(Number(e.target.value))}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-mono tabular-nums text-zinc-900"/></div></div><Button type="submit" variant="primary" className="w-full"><Plus className="w-3.5 h-3.5" /><span>Tạo Tài Khoản Thành Viên</span></Button></form><div className="lg:col-span-7 fliki-card p-5 bg-white space-y-3"><div className="flex items-center justify-between"><h3 className="text-sm font-bold text-zinc-900">Danh Sách Thành Viên & Hạn Mức Sử Dụng ({teamUsers.length})</h3><Badge variant="default" mono>Default Admin: admin@olokaflow.ai / admin123</Badge></div><div className="divide-y divide-zinc-100 border border-zinc-200 rounded-xl overflow-hidden">{teamUsers.map((u) => (<divkey={u.id}className="p-3.5 bg-white flex flex-wrap items-center justify-between gap-2"><div><div className="flex items-center gap-2"><span className="text-xs font-bold text-zinc-900">{u.name}</span><Badgevariant={u.role === 'admin' ? 'crimson' : 'default'}mono>{u.role.toUpperCase()}</Badge></div><div className="text-xs font-mono text-zinc-500 mt-0.5">{u.email} • Đã dùng:{' '}{Number(u.tokensUsed || 0).toLocaleString()} /{' '}{Number(u.tokenQuota || 0).toLocaleString()} tokens</div></div>{u.id !== 'usr-admin' && (<Buttonvariant="danger"size="sm"onClick={async () => {await api.deleteUser(u.id);await loadAllState();}}><Trash2 className="w-3.5 h-3.5" /><span>Xóa</span></Button>)}</div>))}</div></div></div><div className="fliki-card p-6 bg-white space-y-4">65 unmodified lines</div>)}</main>{/* LOGIN MODAL (WHEN CLICKING LOGIN FROM SIDEBAR) */}{showLoginModal && (<div className="fixed inset-0 z-50 bg-zinc-950/50 backdrop-blur-xs flex items-center justify-center p-4"><formonSubmit={handleLoginSubmit}className="fliki-card p-6 bg-white max-w-md w-full space-y-4 shadow-2xl"><div className="flex items-center justify-between border-b border-zinc-100 pb-3"><h3 className="text-base font-bold text-zinc-900">Đăng nhập Tài khoản OlokaFlow</h3><Buttontype="button"variant="ghost"size="sm"onClick={() => setShowLoginModal(false)}>Đóng</Button></div>{loginError && (<div className="p-2.5 rounded-xl bg-rose-50 border border-rose-200 text-xs font-semibold text-[#E11D48]">{loginError}</div>)}<div><label className="block text-xs font-semibold text-zinc-700 mb-1"></label><inputtype="email"value={loginEmail}onChange={(e) => setLoginEmail(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900"required/></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Mật khẩu</label><inputtype="password"value={loginPassword}onChange={(e) => setLoginPassword(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900"required/></div><Buttontype="submit"variant="primary"className="w-full"disabled={loginBusy}><LogIn className="w-3.5 h-3.5" /><span>{loginBusy ? 'Đang đăng nhập...' : 'Đăng Nhập'}</span></Button></form></div>)}</div>);};
9 unmodified lines101112131415161718196 unmodified lines26272829303186 unmodified lines118119120121122123124125126127222 unmodified lines3503513523533543553563573583599 unmodified linesAspectRatio,} from '@olokaflow/shared';async function apiJson<T = any>(url: string, options?: RequestInit): Promise<T> {const resp = await fetch(url, {headers: {'Content-Type': 'application/json',...(options?.headers || {}),},...options,6 unmodified lines}export const api = {// 1. AI Provider Profiles & 4-Tier Live TestergetAIProfiles: () =>apiJson<{ profiles: AIProviderProfile[]; routings: AIRoleRoutingEntry[] }>('/api/ai-profiles'),86 unmodified linesbody: JSON.stringify({ routings }),}),// 2. HyperFrames 4-Tier Catalog & VoicesgetCatalogOverview: () => apiJson<any>('/api/catalog/overview'),getCatalog: () => apiJson<any>('/api/catalog/overview'),getVoices: () => apiJson<{ voices: any[] }>('/api/voices'),searchCatalog: (q: string) =>apiJson<{ items: any[] }>(`/api/catalog/search?q=${encodeURIComponent(q)}`),222 unmodified linesconst ov = await apiJson<any>('/api/admin/overview');return ov.vaultStatus || ov;},getUsers: () => apiJson<{ users: any[] }>('/api/admin/users'),createUser: (payload: any) =>apiJson<{ success: boolean }>('/api/admin/users', {method: 'POST',body: JSON.stringify(payload),}),};9 unmodified lines10111213141516171819202122232425262728293031323334353637383940416 unmodified lines4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989986 unmodified lines186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227222 unmodified lines4504514524534544554564574584594604614624634644654664674684694704714724734744754769 unmodified linesAspectRatio,} from '@olokaflow/shared';const AUTH_TOKEN_KEY = 'olokaflow_auth_token';export function getStoredAuthToken(): string {try {return localStorage.getItem(AUTH_TOKEN_KEY) || '';} catch {return '';}}export function setStoredAuthToken(token: string): void {try {if (token) {localStorage.setItem(AUTH_TOKEN_KEY, token);} else {localStorage.removeItem(AUTH_TOKEN_KEY);}} catch {}}async function apiJson<T = any>(url: string, options?: RequestInit): Promise<T> {const token = getStoredAuthToken();const resp = await fetch(url, {headers: {'Content-Type': 'application/json',...(token ? { Authorization: `Bearer ${token}` } : {}),...(options?.headers || {}),},...options,6 unmodified lines}export const api = {// 0. Auth Login Gate & Team GovernancegetAuthMe: () =>apiJson<{authenticated: boolean;requireAuthGate: boolean;user: {id: string;email: string;name: string;role: string;tokenQuota: number;tokensUsed: number;} | null;}>('/api/auth/me'),login: async (email: string, password: string) => {const res = await apiJson<{token: string;user: {id: string;email: string;name: string;role: string;tokenQuota: number;tokensUsed: number;};}>('/api/auth/login', {method: 'POST',body: JSON.stringify({ email, password }),});if (res.token) {setStoredAuthToken(res.token);}return res;},logout: async () => {await apiJson('/api/auth/logout', { method: 'POST' }).catch(() => {});setStoredAuthToken('');},setAuthGate: (requireAuthGate: boolean) =>apiJson<{ success: boolean; requireAuthGate: boolean }>('/api/auth/gate', {method: 'PUT',body: JSON.stringify({ requireAuthGate }),}),// 1. AI Provider Profiles & 4-Tier Live TestergetAIProfiles: () =>apiJson<{ profiles: AIProviderProfile[]; routings: AIRoleRoutingEntry[] }>('/api/ai-profiles'),86 unmodified linesbody: JSON.stringify({ routings }),}),// 2. HyperFrames 4-Tier Catalog, Voices & Zero-Shot Voice CloninggetCatalogOverview: () => apiJson<any>('/api/catalog/overview'),getCatalog: () => apiJson<any>('/api/catalog/overview'),getVoices: () => apiJson<{ voices: any[]; customVoices?: any[] }>('/api/voices'),cloneCustomVoice: async (params: {file: File;name: string;gender: string;region: string;description?: string;refText?: string;fallbackVoiceId?: string;}) => {const fd = new FormData();fd.append('file', params.file);fd.append('name', params.name);fd.append('gender', params.gender);fd.append('region', params.region);if (params.description) fd.append('description', params.description);if (params.refText) fd.append('refText', params.refText);if (params.fallbackVoiceId) fd.append('fallbackVoiceId', params.fallbackVoiceId);const token = getStoredAuthToken();const resp = await fetch('/api/voices/clone', {method: 'POST',headers: token ? { Authorization: `Bearer ${token}` } : {},body: fd,});const data = await resp.json();if (!resp.ok) throw new Error(data.error || 'Clone giọng đọc thất bại');return data as { success: boolean; voice: any; voices: any[] };},deleteCustomVoice: (id: string) =>apiJson<{ success: boolean; voices: any[] }>(`/api/voices/custom/${id}`, {method: 'DELETE',}),searchCatalog: (q: string) =>apiJson<{ items: any[] }>(`/api/catalog/search?q=${encodeURIComponent(q)}`),222 unmodified linesconst ov = await apiJson<any>('/api/admin/overview');return ov.vaultStatus || ov;},getUsers: () =>apiJson<{ requireAuthGate?: boolean; users: any[] }>('/api/admin/users'),createUser: (payload: any) =>apiJson<{ success: boolean; id: string }>('/api/admin/users', {method: 'POST',body: JSON.stringify(payload),}),deleteUser: (id: string) =>apiJson<{ success: boolean }>(`/api/admin/users/${id}`, {method: 'DELETE',}),// 6. Batch Video Factory (Multi-URL / CSV / Bulk Queue)getBatches: () => apiJson<{ batches: any[] }>('/api/batches'),createBatch: (payload: Record<string, any>) =>apiJson<{ success: boolean; batchId: string; batches: any[] }>('/api/batches', {method: 'POST',body: JSON.stringify(payload),}),deleteBatch: (id: string) =>apiJson<{ success: boolean; batches: any[] }>(`/api/batches/${id}`, {method: 'DELETE',}),};
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507import React, { useState, useEffect } from 'react';import { Layers, Sparkles, Upload, Play, RefreshCw, Film, Download, Trash2, CheckCircle2, Clock, AlertCircle, Cloud, FileSpreadsheet, Plus,} from 'lucide-react';import { api } from '../api';import type { AspectRatio, BrandKit, FrozenRecipe } from '@olokaflow/shared';import { Button, Badge } from './ui/primitives';
interface Props { catalog: any; brands: BrandKit[]; recipes: FrozenRecipe[]; onOpenProjectInStudio: (projectId: string) => void; onRefreshAll: () => void;}
export const BatchStudioView: React.FC<Props> = ({ catalog, brands, recipes, onOpenProjectInStudio, onRefreshAll,}) => { const [batches, setBatches] = useState<any[]>([]); const [batchName, setBatchName] = useState(''); const [bulkLinesText, setBulkLinesText] = useState(''); const [defaultAspectRatio, setDefaultAspectRatio] = useState<AspectRatio>('9:16'); const [defaultVoiceId, setDefaultVoiceId] = useState('Hải Đăng'); const [defaultFramePresetId, setDefaultFramePresetId] = useState( 'editorial-clean-light' ); const [brandKitId, setBrandKitId] = useState(''); const [recipeId, setRecipeId] = useState(''); const [creationMode, setCreationMode] = useState<'auto' | 'storyboard_review'>( 'auto' ); const [autoRenderModal, setAutoRenderModal] = useState(false); const [startingBatch, setStartingBatch] = useState(false);
const voicesList = catalog?.voices || []; const presetsList = catalog?.framePresets || [];
async function loadBatches() { try { const res = await api.getBatches(); setBatches(res.batches || []); } catch {} }
useEffect(() => { void loadBatches(); }, []);
// Poll while any batch is running useEffect(() => { const hasRunning = batches.some((b) => b.status === 'running'); if (!hasRunning) return; const timer = setInterval(() => { void loadBatches(); onRefreshAll(); }, 4000); return () => clearInterval(timer); }, [batches]);
function parseBulkLines(): Array<{ title?: string; prompt: string }> { return bulkLinesText .split(/\r?\n/) .map((line) => line.trim()) .filter((line) => line.length > 0 && !line.startsWith('#')) .map((line) => { // Support "Title | Prompt or URL" or CSV "Title,Prompt" if (line.includes('|')) { const [t, ...rest] = line.split('|'); return { title: t.trim(), prompt: rest.join('|').trim() }; } return { prompt: line }; }); }
function handleCsvFileUpload(e: React.ChangeEvent<HTMLInputElement>) { const file = e.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = () => { const text = String(reader.result || ''); const rows = text .split(/\r?\n/) .map((r) => r.trim()) .filter(Boolean); const converted = rows .filter((r, i) => !(i === 0 && /title|prompt|url/i.test(r))) .map((r) => { const cols = r.split(','); if (cols.length >= 2) { return `${cols[0].replace(/^"|"$/g, '').trim()} | ${cols .slice(1) .join(',') .replace(/^"|"$/g, '') .trim()}`; } return r; }); setBulkLinesText((prev) => prev ? `${prev}\n${converted.join('\n')}` : converted.join('\n') ); }; reader.readAsText(file); e.target.value = ''; }
async function handleStartBatch(e: React.FormEvent) { e.preventDefault(); const items = parseBulkLines(); if (items.length === 0) return; setStartingBatch(true); try { const res = await api.createBatch({ name: batchName.trim() || undefined, items, defaultAspectRatio, defaultVoiceId, defaultFramePresetId, brandKitId: brandKitId || undefined, recipeId: recipeId || undefined, creationMode, autoRenderModal, }); setBatches(res.batches || []); setBulkLinesText(''); setBatchName(''); onRefreshAll(); } catch (err: any) { alert(`Lỗi tạo Batch: ${err.message}`); } finally { setStartingBatch(false); } }
const parsedItemsCount = parseBulkLines().length;
return ( <div className="space-y-6"> {/* Header Banner */} <div className="fliki-card p-6 bg-white flex flex-wrap items-center justify-between gap-4"> <div> <Badge variant="crimson" className="mb-1.5"> <Layers className="w-3 h-3" /> Batch URL-to-Video Factory • Multi-Project Automation </Badge> <h2 className="text-xl font-bold tracking-tight text-zinc-900"> Sản Xuất Video Hàng Loạt Từ Danh Sách URL Sản Phẩm Hoặc CSV </h2> <p className="text-xs text-zinc-500 mt-0.5"> Nhập nhiều link trang web sản phẩm hoặc danh sách kịch bản (mỗi dòng 1 video) — Hệ thống tự động cào ảnh, đọc giọng OlokaTTS, dựng HyperFrames 60fps và tùy chọn xuất MP4 hàng loạt qua Modal Cloud. </p> </div>
<Button type="button" variant="secondary" onClick={() => { setBatchName('Chiến dịch 3 Video Ra mắt Sản phẩm Q4'); setBulkLinesText( [ 'TVC SaaS OlokaFlow | Tạo video quảng cáo ra mắt nền tảng OlokaFlow AI Video Studio dựng đồ họa chuyển động 60fps tự động.', 'Serum Vitamin C Luxury | Giới thiệu tinh chất dưỡng sáng da Vitamin C nguyên chất cấp ẩm 24h, ưu đãi 30% hôm nay.', 'Báo cáo Tăng trưởng Thương mại | Thuyết trình số liệu doanh thu thương mại điện tử tăng 320% và tỷ lệ chuyển đổi đạt 8.4%.', ].join('\n') ); }} > <Sparkles className="w-3.5 h-3.5 text-[#E11D48]" /> <span>Điền Mẫu 3 Video Chiến Dịch</span> </Button> </div>
{/* Batch Configuration Form */} <form onSubmit={handleStartBatch} className="fliki-card p-6 bg-white grid grid-cols-1 lg:grid-cols-12 gap-5" > <div className="lg:col-span-7 space-y-3"> <div className="flex items-center justify-between"> <label className="text-xs font-bold text-zinc-800"> Danh sách Prompt hoặc URL Sản Phẩm (Mỗi dòng 1 Video • Định dạng:{' '} <span className="font-mono text-[#E11D48]"> Tên Video | Nội dung hoặc URL </span> ) </label> <label className="px-2.5 py-1 rounded-lg bg-zinc-100 hover:bg-zinc-200 text-zinc-700 text-[11px] font-semibold flex items-center gap-1.5 cursor-pointer"> <FileSpreadsheet className="w-3.5 h-3.5 text-[#E11D48]" /> <span>Nhập từ CSV / TXT</span> <input type="file" accept=".csv,.txt" onChange={handleCsvFileUpload} className="hidden" /> </label> </div>
<textarea rows={7} value={bulkLinesText} onChange={(e) => setBulkLinesText(e.target.value)} placeholder={`Ví dụ:\nVideo Sản phẩm 1 | https://example.com/san-pham-1 Giới thiệu ưu điểm nổi bật và khuyến mãi\nVideo Sản phẩm 2 | Tạo video quảng cáo tai nghe chống ồn chủ động ANC pin 40 giờ\nVideo Sản phẩm 3 | Báo cáo kết quả kinh doanh quý 4 tăng trưởng vượt bậc`} className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-xs font-mono text-zinc-900 leading-relaxed focus:outline-none focus:border-[#E11D48] focus:bg-white" required />
<div className="flex items-center justify-between text-xs text-zinc-500"> <span> Số lượng video nhận diện:{' '} <strong className="font-mono tabular-nums text-[#E11D48]"> {parsedItemsCount} video </strong> </span> <span>Tự động cào ảnh nếu dòng chứa link http/https</span> </div> </div>
<div className="lg:col-span-5 bg-zinc-50/80 border border-zinc-200/80 rounded-2xl p-4 space-y-3 flex flex-col justify-between"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> <div className="sm:col-span-2"> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Tên lô sản xuất (Batch Name) </label> <input type="text" value={batchName} onChange={(e) => setBatchName(e.target.value)} placeholder="VD: Lô 10 Video TikTok Sản phẩm Mới..." className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs text-zinc-900" /> </div>
<div> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Tỷ lệ khung hình </label> <select value={defaultAspectRatio} onChange={(e) => setDefaultAspectRatio(e.target.value as AspectRatio) } className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800" > <option value="9:16">9:16 Dọc (TikTok / Reels)</option> <option value="16:9">16:9 Ngang (YouTube)</option> <option value="1:1">1:1 Vuông (Feed)</option> </select> </div>
<div> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Phong cách (Frame Preset) </label> <select value={defaultFramePresetId} onChange={(e) => setDefaultFramePresetId(e.target.value)} className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800" > {presetsList.map((fp: any) => ( <option key={fp.id} value={fp.id}> {fp.name} </option> ))} </select> </div>
<div className="sm:col-span-2"> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Giọng đọc mặc định (Bao gồm 25 Giọng OlokaTTS & Giọng Clone) </label> <select value={defaultVoiceId} onChange={(e) => setDefaultVoiceId(e.target.value)} className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800" > {voicesList.map((v: any) => ( <option key={v.id} value={v.voiceId || v.id}> {v.name} — {v.description} </option> ))} </select> </div>
<div> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Brand Kit </label> <select value={brandKitId} onChange={(e) => setBrandKitId(e.target.value)} className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800" > <option value="">Mặc định theo Preset</option> {brands.map((b) => ( <option key={b.id} value={b.id}> {b.name} </option> ))} </select> </div>
<div> <label className="block text-xs font-semibold text-zinc-700 mb-1"> Frozen Recipe </label> <select value={recipeId} onChange={(e) => setRecipeId(e.target.value)} className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800" > <option value="">Tự động chọn Blueprint</option> {recipes.map((r) => ( <option key={r.id} value={r.id}> {r.name} </option> ))} </select> </div> </div>
<div className="pt-3 border-t border-zinc-200/80 space-y-3"> <label className="flex items-center gap-2 text-xs font-semibold text-zinc-700 cursor-pointer"> <input type="checkbox" checked={autoRenderModal} onChange={(e) => setAutoRenderModal(e.target.checked)} className="rounded border-zinc-300 text-[#E11D48] focus:ring-[#E11D48]" /> <Cloud className="w-3.5 h-3.5 text-[#E11D48]" /> <span> Tự động gửi Render MP4 lên Modal Cloud (cpu24w22) sau khi dựng xong </span> </label>
<Button type="submit" variant="primary" size="lg" className="w-full" disabled={startingBatch || parsedItemsCount === 0} > <Play className="w-4 h-4 fill-current" /> <span> {startingBatch ? 'Đang khởi chạy hàng đợi...' : `Khởi Chạy Sản Xuất ${parsedItemsCount} Video Hàng Loạt`} </span> </Button> </div> </div> </form>
{/* Active & Completed Batch Queue */} <div className="space-y-4"> <div className="flex items-center justify-between"> <h3 className="text-sm font-bold text-zinc-900"> Tiến Trình & Lịch Sử Lô Sản Xuất Video ({batches.length}) </h3> <Button variant="secondary" size="sm" onClick={() => loadBatches()}> <RefreshCw className="w-3.5 h-3.5" /> <span>Làm mới trạng thái</span> </Button> </div>
{batches.length === 0 ? ( <div className="fliki-card p-8 bg-white text-center text-xs text-zinc-400"> Chưa có lô sản xuất hàng loạt nào. Hãy nhập danh sách URL/Prompt ở trên hoặc bấm "Điền Mẫu 3 Video Chiến Dịch" để bắt đầu. </div> ) : ( batches.map((batch) => { const pct = batch.totalItems > 0 ? Math.round((batch.completedItems / batch.totalItems) * 100) : 0; return ( <div key={batch.id} className="fliki-card p-5 bg-white space-y-4"> <div className="flex flex-wrap items-center justify-between gap-3 border-b border-zinc-100 pb-3"> <div> <div className="flex items-center gap-2"> <span className="text-sm font-bold text-zinc-900"> {batch.name} </span> <Badge variant={ batch.status === 'completed' ? 'emerald' : batch.status === 'failed' ? 'crimson' : 'amber' } mono > {batch.status === 'running' ? ( <RefreshCw className="w-3 h-3 animate-spin" /> ) : ( <CheckCircle2 className="w-3 h-3" /> )} {batch.completedItems}/{batch.totalItems} HOÀN TẤT ({pct}%) </Badge> </div> <div className="text-[11px] font-mono text-zinc-400 mt-0.5"> ID: {batch.id} • Khung hình: {batch.config?.defaultAspectRatio}{' '} • Giọng: {batch.config?.defaultVoiceId} </div> </div>
<Button variant="danger" size="sm" onClick={async () => { const res = await api.deleteBatch(batch.id); setBatches(res.batches || []); }} > <Trash2 className="w-3.5 h-3.5" /> <span>Xóa lô</span> </Button> </div>
<div className="divide-y divide-zinc-100 border border-zinc-200 rounded-xl overflow-hidden"> {(batch.items || []).map((it: any, idx: number) => ( <div key={idx} className="p-3.5 bg-white hover:bg-zinc-50/70 flex flex-wrap items-center justify-between gap-3" > <div className="space-y-0.5 max-w-2xl"> <div className="flex items-center gap-2"> <span className="px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-700 font-mono tabular-nums text-[11px] font-bold"> #{String(idx + 1).padStart(2, '0')} </span> <span className="text-xs font-bold text-zinc-900"> {it.projectTitle} </span> <Badge variant={ it.status === 'ready' || it.status === 'rendered' ? 'emerald' : it.status === 'error' ? 'crimson' : 'amber' } mono > {it.status} </Badge> {it.totalDurationSec > 0 && ( <span className="text-[11px] font-mono tabular-nums text-zinc-400"> {it.sceneCount} cảnh • {Math.round(it.totalDurationSec)}s </span> )} </div> <p className="text-xs text-zinc-500 line-clamp-1"> {it.prompt} </p> </div>
<div className="flex items-center gap-2"> {it.renderOutputUrl && ( <a href={it.renderOutputUrl} download className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold flex items-center gap-1" > <Download className="w-3 h-3" /> <span>Tải MP4</span> </a> )} {it.projectId && ( <Button variant="secondary" size="sm" onClick={() => onOpenProjectInStudio(it.projectId)} > <Film className="w-3.5 h-3.5 text-[#E11D48]" /> <span>Mở trong Studio</span> </Button> )} </div> </div> ))} </div> </div> ); }) )} </div> </div> );};9 unmodified lines10111213141516171819202122232425262 unmodified lines29303132333410 unmodified lines45464748495013 unmodified lines6465666768697071727374757677787980818283848586878889909133 unmodified lines1251261271281291301316 unmodified lines1381391401411421437 unmodified lines1511521531541551561571586 unmodified lines1651661671681691709 unmodified linesStar,Sparkles,Search,} from 'lucide-react';import { Button, Badge } from './ui/primitives';interface Props {catalog: any;initialSubTab?: 'voices' | 'presets' | 'blueprints' | 'motion' | 'registry';}export const CatalogBrowserView: React.FC<Props> = ({catalog,initialSubTab = 'voices',}) => {const [subTab, setSubTab] = useState<'voices' | 'presets' | 'blueprints' | 'motion' | 'registry'2 unmodified linesconst audioRef = useRef<HTMLAudioElement | null>(null);const [playingVoiceUrl, setPlayingVoiceUrl] = useState('');React.useEffect(() => {setSubTab(initialSubTab);}, [initialSubTab]);10 unmodified linessetPlayingVoiceUrl(url);}const voices = catalog?.voices || [];const presets = catalog?.framePresets || [];const blueprints = catalog?.sceneBlueprints || [];13 unmodified lines<div><Badge variant="crimson" className="mb-1.5"><Sparkles className="w-3 h-3" />Kho Giọng Đọc OlokaTTS & HyperFrames 4-Tier Catalog</Badge><h2 className="text-xl font-bold tracking-tight text-zinc-900">Thư Viện 25 Giọng Đọc AI Tiếng Việt, 13 Frame Presets, 22 Blueprints & 45+ Motion Rules</h2><p className="text-xs text-zinc-500 mt-0.5">Nghe thử trực tiếp 25 giọng đọc tiếng Việt tự nhiên từ https://tts.oloka.net và khám phá toàn bộ kho chuyển động HyperFrames.</p></div><div className="relative w-72"><Search className="w-3.5 h-3.5 text-zinc-400 absolute left-3.5 top-1/2 -translate-y-1/2" /><inputtype="text"value={search}onChange={(e) => setSearch(e.target.value)}placeholder="Tìm giọng đọc, Blueprint, hiệu ứng..."className="w-full bg-zinc-50 border border-zinc-200 rounded-xl pl-9 pr-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"/></div></div>{/* Sub-navigation Tabs */}<div className="flex flex-wrap gap-2">{[33 unmodified lines})}</div>{/* TAB 1: 25 LIVE OLOKATTS VIETNAMESE VOICES + OPENAI VOICES */}{subTab === 'voices' && (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">{voices6 unmodified lines).map((v: any) => {const isPlaying = playingVoiceUrl && playingVoiceUrl === v.previewUrl;return (<divkey={v.id}7 unmodified lines{v.name}</span><div className="flex items-center gap-1.5 mt-1.5 flex-wrap"><Badge variant="crimson">{v.provider === 'olokatts' ? 'OlokaTTS v3' : 'OpenAI TTS'}</Badge><Badge variant="default">{v.gender} • {v.region}6 unmodified lines)}</div></div></div><p className="text-xs text-zinc-600 mt-2">{v.description}</p></div>9 unmodified lines1011121314151617181920212223242526272829303132332 unmodified lines363738394041424344454647484950515210 unmodified lines63646566676869707172737475767778798081828384858687888990919293949513 unmodified lines10911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330433 unmodified lines3383393403413423433446 unmodified lines3513523533543553563577 unmodified lines3653663673683693703713723733743753766 unmodified lines3833843853863873883893903913923933943953963973983994004014029 unmodified linesStar,Sparkles,Search,Upload,Plus,Trash2,X,} from 'lucide-react';import { api } from '../api';import { Button, Badge } from './ui/primitives';interface Props {catalog: any;initialSubTab?: 'voices' | 'presets' | 'blueprints' | 'motion' | 'registry';onRefreshCatalog?: () => void;}export const CatalogBrowserView: React.FC<Props> = ({catalog,initialSubTab = 'voices',onRefreshCatalog,}) => {const [subTab, setSubTab] = useState<'voices' | 'presets' | 'blueprints' | 'motion' | 'registry'2 unmodified linesconst audioRef = useRef<HTMLAudioElement | null>(null);const [playingVoiceUrl, setPlayingVoiceUrl] = useState('');// Zero-Shot Voice Cloning Drawer Stateconst [showCloneDrawer, setShowCloneDrawer] = useState(false);const [cloneName, setCloneName] = useState('');const [cloneGender, setCloneGender] = useState('Nam');const [cloneRegion, setCloneRegion] = useState('Nam');const [cloneDescription, setCloneDescription] = useState('');const [cloneRefText, setCloneRefText] = useState('');const [cloneFallbackVoiceId, setCloneFallbackVoiceId] = useState('Hải Đăng');const [cloneFile, setCloneFile] = useState<File | null>(null);const [cloningBusy, setCloningBusy] = useState(false);React.useEffect(() => {setSubTab(initialSubTab);}, [initialSubTab]);10 unmodified linessetPlayingVoiceUrl(url);}async function handleCloneVoiceSubmit(e: React.FormEvent) {e.preventDefault();if (!cloneFile || !cloneName.trim()) return;setCloningBusy(true);try {await api.cloneCustomVoice({file: cloneFile,name: cloneName.trim(),gender: cloneGender,region: cloneRegion,description: cloneDescription.trim() || undefined,refText: cloneRefText.trim() || undefined,fallbackVoiceId: cloneFallbackVoiceId,});setCloneName('');setCloneDescription('');setCloneRefText('');setCloneFile(null);setShowCloneDrawer(false);onRefreshCatalog?.();} catch (err: any) {alert(`Lỗi Clone giọng đọc: ${err.message}`);} finally {setCloningBusy(false);}}const voices = catalog?.voices || [];const presets = catalog?.framePresets || [];const blueprints = catalog?.sceneBlueprints || [];13 unmodified lines<div><Badge variant="crimson" className="mb-1.5"><Sparkles className="w-3 h-3" />Kho Giọng Đọc OlokaTTS, Voice Cloning & HyperFrames 4-Tier Catalog</Badge><h2 className="text-xl font-bold tracking-tight text-zinc-900">Thư Viện 25 Giọng Đọc AI Tiếng Việt, Clone Giọng Cá Nhân & Kho Hiệu Ứng</h2><p className="text-xs text-zinc-500 mt-0.5">Nghe thử trực tiếp 25 giọng đọc tiếng Việt tự nhiên từ https://tts.oloka.net, tải lên file âm thanh mẫu (.wav/.mp3) để Clone giọng riêng và khám phá kho chuyển động HyperFrames.</p></div><div className="flex items-center gap-2.5 flex-wrap"><div className="relative w-64"><Search className="w-3.5 h-3.5 text-zinc-400 absolute left-3.5 top-1/2 -translate-y-1/2" /><inputtype="text"value={search}onChange={(e) => setSearch(e.target.value)}placeholder="Tìm giọng đọc, Blueprint, hiệu ứng..."className="w-full bg-zinc-50 border border-zinc-200 rounded-xl pl-9 pr-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"/></div><Buttontype="button"variant="primary"onClick={() => {setSubTab('voices');setShowCloneDrawer(!showCloneDrawer);}}><Plus className="w-3.5 h-3.5" /><span>{showCloneDrawer? 'Đóng Khung Clone Giọng': 'Clone Giọng Mới (.WAV/.MP3)'}</span></Button></div></div>{/* ZERO-SHOT VOICE CLONING STUDIO DRAWER */}{showCloneDrawer && (<formonSubmit={handleCloneVoiceSubmit}className="fliki-card p-6 bg-white border-rose-200 space-y-4"><div className="flex items-center justify-between border-b border-zinc-100 pb-3"><div><h3 className="text-base font-bold text-zinc-900 flex items-center gap-2"><Mic className="w-4 h-4 text-[#E11D48]" /><span>Zero-Shot Voice Cloning Studio (Tạo Giọng Đọc Cá Nhân Hóa)</span></h3><p className="text-xs text-zinc-500 mt-0.5">Tải lên đoạn thu âm mẫu (5–30 giây, rõ chữ, không tạp âm). Giọng Clone sẽ xuất hiện ngay trong danh sách chọn giọng của Fliki Video Studio & Batch Video Factory.</p></div><Buttontype="button"variant="ghost"size="sm"onClick={() => setShowCloneDrawer(false)}><X className="w-3.5 h-3.5" /><span>Đóng</span></Button></div><div className="grid grid-cols-1 md:grid-cols-12 gap-4"><div className="md:col-span-4 space-y-3"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Tên giọng đọc Clone *</label><inputtype="text"value={cloneName}onChange={(e) => setCloneName(e.target.value)}placeholder="VD: Giọng CEO Phúc (Miền Nam)..."className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"required/></div><div className="grid grid-cols-2 gap-2"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Giới tính</label><selectvalue={cloneGender}onChange={(e) => setCloneGender(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"><option value="Nam">Nam</option><option value="Nữ">Nữ</option></select></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Vùng miền</label><selectvalue={cloneRegion}onChange={(e) => setCloneRegion(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"><option value="Nam">Miền Nam</option><option value="Bắc">Miền Bắc</option><option value="Trung">Miền Trung</option></select></div></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Giọng OlokaTTS đồng điệu dự phòng</label><selectvalue={cloneFallbackVoiceId}onChange={(e) => setCloneFallbackVoiceId(e.target.value)}className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800">{voices.filter((v: any) => v.provider === 'olokatts').map((v: any) => (<option key={v.id} value={v.voiceId}>{v.name}</option>))}</select></div></div><div className="md:col-span-8 space-y-3 flex flex-col justify-between"><div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Tệp âm thanh mẫu (.WAV, .MP3, .M4A) *</label><label className="flex items-center justify-center gap-2 w-full h-24 rounded-xl border-2 border-dashed border-zinc-300 hover:border-[#E11D48] bg-zinc-50 px-3 text-xs text-zinc-600 cursor-pointer transition-colors"><Upload className="w-4 h-4 text-[#E11D48]" /><span className="truncate font-semibold">{cloneFile? `${cloneFile.name} (${(cloneFile.size / 1024).toFixed(0)} KB)`: 'Bấm để chọn file giọng mẫu (.wav / .mp3)'}</span><inputtype="file"accept="audio/*,.wav,.mp3,.m4a"onChange={(e) => setCloneFile(e.target.files?.[0] || null)}className="hidden"required/></label></div><div><label className="block text-xs font-semibold text-zinc-700 mb-1">Nội dung văn bản của file mẫu (Reference Transcript)</label><textarearows={3}value={cloneRefText}onChange={(e) => setCloneRefText(e.target.value)}placeholder="Nhập chính xác câu nói trong đoạn ghi âm mẫu để tăng độ chuẩn xác khi Zero-Shot Clone..."className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-2.5 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"/></div></div><div className="flex items-center justify-between gap-3 pt-2"><inputtype="text"value={cloneDescription}onChange={(e) => setCloneDescription(e.target.value)}placeholder="Mô tả phong cách giọng (VD: Trầm ấm, thuyết trình công nghệ, tốc độ vừa phải)..."className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900"/><Button type="submit" variant="primary" disabled={cloningBusy || !cloneFile}><Mic className="w-3.5 h-3.5" /><span>{cloningBusy ? 'Đang lưu giọng Clone...' : 'Lưu Giọng Clone Vào Hệ Thống'}</span></Button></div></div></div></form>)}{/* Sub-navigation Tabs */}<div className="flex flex-wrap gap-2">{[33 unmodified lines})}</div>{/* TAB 1: CUSTOM CLONED VOICES + 25 LIVE OLOKATTS VIETNAMESE VOICES + OPENAI VOICES */}{subTab === 'voices' && (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">{voices6 unmodified lines).map((v: any) => {const isPlaying = playingVoiceUrl && playingVoiceUrl === v.previewUrl;const isCloned = v.provider === 'cloned';return (<divkey={v.id}7 unmodified lines{v.name}</span><div className="flex items-center gap-1.5 mt-1.5 flex-wrap"><Badge variant={isCloned ? 'emerald' : 'crimson'}>{isCloned? 'Zero-Shot Cloned': v.provider === 'olokatts'? 'OlokaTTS v3': 'OpenAI TTS'}</Badge><Badge variant="default">{v.gender} • {v.region}6 unmodified lines)}</div></div>{isCloned && (<buttontype="button"onClick={async () => {await api.deleteCustomVoice(v.id);onRefreshCatalog?.();}}className="p-1.5 rounded-lg hover:bg-rose-50 text-zinc-400 hover:text-[#E11D48] cursor-pointer"title="Xóa giọng Clone này"><Trash2 className="w-3.5 h-3.5" /></button>)}</div><p className="text-xs text-zinc-600 mt-2">{v.description}</p></div>
apps/server/src/db/database.ts+27
apps/server/src/index.ts+358-5
apps/server/src/services/voiceService.ts+114-10
apps/web/src/App.tsx+509-46
apps/web/src/api.ts+121-4
apps/web/src/components/BatchStudioView.tsxAdded+507
apps/web/src/components/CatalogBrowserView.tsx+247-15