Spaces:
Sleeping

olokaflow / apps /web /src /components /BatchStudioView.tsx
phucsd's picture
feat(enterprise): add Batch URL/CSV Video Factory, Zero-Shot Voice Cloning Studio & Auth Login Gate
8d2c959 verified
Raw History Blame Contribute Delete
20.1 kB
import 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>
);
};