titusgiap Claude Opus 4.8 commited on
Commit
788bc93
·
1 Parent(s): 0172658

feat(text): thêm tab "Chèn chữ vào video" (nhiều video) + nhận dạng lời (ASR)

Browse files

- Tab mới /chen-chu: vào 1..N video, chèn chữ hard-sub, ra N video tương ứng.
- Dùng lại SubtitleEditor (đủ phông/màu/11 kiểu nền/3 kiểu hiển thị/kéo thả)
qua props tùy chọn initialSegs/initialMode/onChange/headerExtra/onFetchLines
(mặc định null -> tab Dịch/đổi giọng không đổi).
- Lấy text: nút "Tự lấy lời từ video (nhận dạng)" -> ASR Whisper (Groq) không
dịch, đổ lời + mốc vào editor để sửa; hoặc gõ tay.
- Áp form giữa các video: "Áp cả lời + kiểu" (cùng nội dung) và "Áp kiểu (giữ
lời riêng)" (mỗi video tự nhận dạng lời khác nhau).
- Backend: endpoint /api/dub/subtitle/transcribe (extract_tracks + asr, nhẹ);
burn + preview-frame ra thư mục RIÊNG theo từng video (hash) -> burn nhiều
video 1 phiên không đè nhau.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

backend/app/api/dub.py CHANGED
@@ -520,6 +520,56 @@ def tts_from_text(req: TtsReq):
520
  return {"job_id": job.id, "session": sid}
521
 
522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
  # --------------------------------------------------- HARD SUBTITLE ---
524
 
525
  class SubPlanReq(BaseModel):
@@ -574,16 +624,22 @@ def subtitle_burn(req: SubBurnReq):
574
  segs.append({"start": s.start, "end": s.end, "text": s.text,
575
  "style": s.style, "breaks": s.breaks,
576
  "words": sub.words_for(s.text, s.start, s.end)})
577
- out_dir = sub_dir(req.session, "subtitled")
 
 
 
 
 
 
578
  ass = os.path.join(out_dir, "sub.ass")
579
  sub.build_ass(segs, ass, mode=req.mode, res=res)
580
  h.item_status(it, "running", detail="Đang burn phụ đề (ffmpeg)")
581
  h.set_progress(0.3)
582
- name = "video_subtitled.mp4"
583
  out = os.path.join(out_dir, name)
584
  sub.burn(vid, ass, out)
585
  result = {"name": name,
586
- "video_url": f"/api/files/{req.session}/subtitled/{name}"}
587
  h.item_status(it, "done", detail="xong", result=result)
588
  h.set_progress(1.0)
589
  return {"session": req.session, "output": result}
@@ -624,11 +680,15 @@ def subtitle_preview_frame(req: SubFrameReq):
624
  if not os.path.exists(vid):
625
  raise HTTPException(status_code=404, detail="Không thấy video")
626
  res = sub.probe_size(vid)
627
- out_dir = sub_dir(req.session, "subprev")
 
 
 
 
628
  ass = os.path.join(out_dir, "prev.ass")
629
  sub.build_ass(_sub_segs(req.segments), ass, mode=req.mode, res=res)
630
  png = os.path.join(out_dir, "prev.png")
631
  sub.render_frame(vid, ass, req.time, png)
632
  import time as _t
633
- return {"image_url": f"/api/files/{req.session}/subprev/prev.png",
634
  "v": int(_t.time() * 1000)} # cache-buster cho <img>
 
520
  return {"job_id": job.id, "session": sid}
521
 
522
 
523
+ # ------------------------------- NHẬN DẠNG LỜI TỪ VIDEO (ASR, không dịch) ---
524
+
525
+ class SubTranscribeReq(BaseModel):
526
+ session: str
527
+ video: str # rel path video cần lấy lời
528
+ no_speech_max: float = 0.6
529
+ logprob_min: float = -1.0
530
+
531
+
532
+ @router.post("/subtitle/transcribe")
533
+ def subtitle_transcribe(req: SubTranscribeReq):
534
+ """Nhận dạng LỜI GỐC trong video (Whisper) -> danh sách câu + mốc, KHÔNG dịch.
535
+
536
+ Dùng cho tab 'Chèn chữ vào video': đổ sẵn lời thoại vào trình chèn chữ để user
537
+ sửa & tạo kiểu, thay vì gõ tay. Chỉ tách audio 16k mono (không demucs/không TTS)
538
+ nên nhẹ. Cần GROQ_API_KEY (giống bước ASR của lồng tiếng).
539
+ """
540
+ import hashlib
541
+ job = jobs.create("subtitle")
542
+
543
+ def work(h):
544
+ it = h.add_item("transcribe")
545
+ try:
546
+ from ..services.dubber import audio as _audio, asr as _asr
547
+ vid = os.path.join(session_dir(req.session), req.video)
548
+ if not os.path.exists(vid):
549
+ raise FileNotFoundError("Không thấy video")
550
+ key = hashlib.md5(req.video.encode("utf-8")).hexdigest()[:8]
551
+ work_dir = sub_dir(req.session, "asr_work", key)
552
+ h.item_status(it, "running", detail="Tách audio")
553
+ h.set_progress(0.15)
554
+ asr_wav, _full = _audio.extract_tracks(vid, work_dir)
555
+ h.item_status(it, "running", detail="Nhận dạng lời (Whisper)")
556
+ h.set_progress(0.45)
557
+ segs, language = _asr.transcribe(
558
+ asr_wav, no_speech_max=req.no_speech_max, logprob_min=req.logprob_min)
559
+ lines = [{"start": float(s.start), "end": float(s.end),
560
+ "text": (s.text or "").strip()} for s in segs if (s.text or "").strip()]
561
+ result = {"lines": lines, "language": language, "n": len(lines)}
562
+ h.item_status(it, "done", detail=f"{len(lines)} câu · {language}", result=result)
563
+ h.set_progress(1.0)
564
+ return {"session": req.session, "output": result}
565
+ except Exception as e:
566
+ h.item_status(it, "error", error=str(e))
567
+ return {"session": req.session, "error": str(e)}
568
+
569
+ jobs.submit(job, work)
570
+ return {"job_id": job.id, "session": req.session}
571
+
572
+
573
  # --------------------------------------------------- HARD SUBTITLE ---
574
 
575
  class SubPlanReq(BaseModel):
 
624
  segs.append({"start": s.start, "end": s.end, "text": s.text,
625
  "style": s.style, "breaks": s.breaks,
626
  "words": sub.words_for(s.text, s.start, s.end)})
627
+ # Thư mục ra RIÊNG cho từng video nguồn (theo tên + hash đường dẫn) ->
628
+ # burn NHIỀU video trong 1 phiên không ghi đè lên nhau (tab "Chèn chữ").
629
+ import hashlib
630
+ vbase = os.path.splitext(os.path.basename(req.video))[0]
631
+ safe = (re.sub(r"[^0-9A-Za-z_.-]+", "_", vbase) or "video")[:40]
632
+ key = safe + "_" + hashlib.md5(req.video.encode("utf-8")).hexdigest()[:6]
633
+ out_dir = sub_dir(req.session, "subtitled", key)
634
  ass = os.path.join(out_dir, "sub.ass")
635
  sub.build_ass(segs, ass, mode=req.mode, res=res)
636
  h.item_status(it, "running", detail="Đang burn phụ đề (ffmpeg)")
637
  h.set_progress(0.3)
638
+ name = f"{safe}_sub.mp4"
639
  out = os.path.join(out_dir, name)
640
  sub.burn(vid, ass, out)
641
  result = {"name": name,
642
+ "video_url": f"/api/files/{req.session}/subtitled/{key}/{name}"}
643
  h.item_status(it, "done", detail="xong", result=result)
644
  h.set_progress(1.0)
645
  return {"session": req.session, "output": result}
 
680
  if not os.path.exists(vid):
681
  raise HTTPException(status_code=404, detail="Không thấy video")
682
  res = sub.probe_size(vid)
683
+ # Khung xem trước RIÊNG cho từng video (theo hash đường dẫn) -> xem trước nhiều
684
+ # video trong 1 phiên không đá nhau (ảnh cũ của video khác đè lên).
685
+ import hashlib
686
+ key = hashlib.md5(req.video.encode("utf-8")).hexdigest()[:8]
687
+ out_dir = sub_dir(req.session, "subprev", key)
688
  ass = os.path.join(out_dir, "prev.ass")
689
  sub.build_ass(_sub_segs(req.segments), ass, mode=req.mode, res=res)
690
  png = os.path.join(out_dir, "prev.png")
691
  sub.render_frame(vid, ass, req.time, png)
692
  import time as _t
693
+ return {"image_url": f"/api/files/{req.session}/subprev/{key}/prev.png",
694
  "v": int(_t.time() * 1000)} # cache-buster cho <img>
frontend/src/App.jsx CHANGED
@@ -10,6 +10,7 @@ const DownList = lazy(() => import("./pages/DownList"));
10
  const CutVideo = lazy(() => import("./pages/CutVideo"));
11
  const ShuffleVideo = lazy(() => import("./pages/ShuffleVideo"));
12
  const DubVideo = lazy(() => import("./pages/DubVideo"));
 
13
  const Guide = lazy(() => import("./pages/Guide"));
14
  const Support = lazy(() => import("./pages/Support"));
15
  const Placeholder = lazy(() => import("./pages/Placeholder"));
@@ -34,6 +35,7 @@ const router = createBrowserRouter([
34
  { path: "/cut", element: <CutVideo /> },
35
  { path: "/xao", element: <ShuffleVideo /> },
36
  { path: "/dub", element: <DubVideo /> },
 
37
  { path: "/listing-anh", element: <ListingImage /> },
38
  // { path: "/listing-free", element: <ListingFree /> }, // Ẩn tạm Listing ảnh Free
39
  { path: "/flux2", element: <Flux2Gen /> },
 
10
  const CutVideo = lazy(() => import("./pages/CutVideo"));
11
  const ShuffleVideo = lazy(() => import("./pages/ShuffleVideo"));
12
  const DubVideo = lazy(() => import("./pages/DubVideo"));
13
+ const TextVideo = lazy(() => import("./pages/TextVideo"));
14
  const Guide = lazy(() => import("./pages/Guide"));
15
  const Support = lazy(() => import("./pages/Support"));
16
  const Placeholder = lazy(() => import("./pages/Placeholder"));
 
35
  { path: "/cut", element: <CutVideo /> },
36
  { path: "/xao", element: <ShuffleVideo /> },
37
  { path: "/dub", element: <DubVideo /> },
38
+ { path: "/chen-chu", element: <TextVideo /> },
39
  { path: "/listing-anh", element: <ListingImage /> },
40
  // { path: "/listing-free", element: <ListingFree /> }, // Ẩn tạm Listing ảnh Free
41
  { path: "/flux2", element: <Flux2Gen /> },
frontend/src/api.js CHANGED
@@ -114,6 +114,8 @@ export const api = {
114
  dubTts: (req) => jpost("/api/dub/tts", req),
115
  // Nạp SRT tự tải (thay bản dịch tự động) — trả lines đã bỏ nhãn [tên]
116
  dubSrtImport: (file, session) => upload("/api/dub/subtitle/import", file, { session }),
 
 
117
  // Hard subtitle
118
  subtitlePlan: (session, srt) => jpost("/api/dub/subtitle/plan", { session, srt }),
119
  subtitleBurn: (req) => jpost("/api/dub/subtitle", req),
 
114
  dubTts: (req) => jpost("/api/dub/tts", req),
115
  // Nạp SRT tự tải (thay bản dịch tự động) — trả lines đã bỏ nhãn [tên]
116
  dubSrtImport: (file, session) => upload("/api/dub/subtitle/import", file, { session }),
117
+ // Nhận dạng lời gốc trong video (ASR, không dịch) — cho tab "Chèn chữ vào video"
118
+ dubTranscribe: (req) => jpost("/api/dub/subtitle/transcribe", req),
119
  // Hard subtitle
120
  subtitlePlan: (session, srt) => jpost("/api/dub/subtitle/plan", { session, srt }),
121
  subtitleBurn: (req) => jpost("/api/dub/subtitle", req),
frontend/src/components/Sidebar.jsx CHANGED
@@ -1,7 +1,7 @@
1
  import { NavLink } from "react-router-dom";
2
  import {
3
  IcHome, IcDownload, IcImage, IcVideo, IcScissors, IcShuffle, IcMic,
4
- IcBook, IcHelp, IcLock, IcHistory, IcStar,
5
  } from "./Icons";
6
 
7
  const item = (to, Icon, label) => (
@@ -36,6 +36,7 @@ export default function Sidebar() {
36
  {item("/cut", IcScissors, "Cut video")}
37
  {item("/xao", IcShuffle, "Xào video")}
38
  {item("/dub", IcMic, "Dịch / đổi giọng")}
 
39
  {item("/lich-su", IcHistory, "Lịch sử cá nhân")}
40
  </div>
41
 
 
1
  import { NavLink } from "react-router-dom";
2
  import {
3
  IcHome, IcDownload, IcImage, IcVideo, IcScissors, IcShuffle, IcMic,
4
+ IcBook, IcHelp, IcLock, IcHistory, IcStar, IcText,
5
  } from "./Icons";
6
 
7
  const item = (to, Icon, label) => (
 
36
  {item("/cut", IcScissors, "Cut video")}
37
  {item("/xao", IcShuffle, "Xào video")}
38
  {item("/dub", IcMic, "Dịch / đổi giọng")}
39
+ {item("/chen-chu", IcText, "Chèn chữ vào video")}
40
  {item("/lich-su", IcHistory, "Lịch sử cá nhân")}
41
  </div>
42
 
frontend/src/components/SubtitleEditor.jsx CHANGED
@@ -47,10 +47,20 @@ const wordsFor = (text, start, end) => {
47
  let t = start; return words.map((w, i) => { const wd = dur * wt[i] / tot; const o = { w, start: t, end: t + wd }; t += wd; return o; });
48
  };
49
 
50
- export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, username, onClose }) {
51
- const [segs, setSegs] = useState([]); // {start,end,text,words,locked,style}
 
 
 
 
 
 
 
 
 
 
52
  const [sel, setSel] = useState(0);
53
- const [mode, setMode] = useState("whole");
54
  const [playing, setPlaying] = useState(false);
55
  const [t, setT] = useState(0);
56
  const [dur, setDur] = useState(0);
@@ -81,6 +91,28 @@ export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, us
81
  const pollAbort = useRef(new AbortController());
82
  useEffect(() => () => pollAbort.current.abort(), []);
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  // Tự sinh phụ đề từ lời dịch (SRT). User bấm nút này khi muốn.
85
  const autoSubtitle = async () => {
86
  try {
@@ -247,6 +279,16 @@ export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, us
247
  start: s.start, end: s.end, text: s.text, style: s.style, breaks: measureBreaks(s),
248
  }));
249
 
 
 
 
 
 
 
 
 
 
 
250
  const burn = async () => {
251
  if (!segs.length) return alert("Chưa có đoạn text nào. Bấm 'Tự tạo phụ đề' hoặc 'Thêm text'.");
252
  setBusy(true); setResult(null);
@@ -365,9 +407,12 @@ export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, us
365
 
366
  return (
367
  <div className="card" style={{ borderColor: "var(--orange)" }}>
368
- <div className="flex between center">
369
- <div className="panel-title" style={{ margin: 0 }}>Chèn phụ đề (hard sub)</div>
370
- <button className="btn sm ghost" onClick={onClose}>Đóng</button>
 
 
 
371
  </div>
372
 
373
  <div className="grid-2" style={{ gridTemplateColumns: "300px 1fr", gap: 16, marginTop: 10 }}>
@@ -459,9 +504,15 @@ export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, us
459
 
460
  {/* controls */}
461
  <div className="stack" style={{ gap: 12 }}>
462
- {segs.filter((s) => s.locked).length === 0 && (
463
  <button className="btn primary" onClick={autoSubtitle}>Tự tạo phụ đề từ lời dịch</button>
464
  )}
 
 
 
 
 
 
465
  <div className="flex gap8 center">
466
  <button className="btn sm ghost" onClick={delText} style={{ display: cur() && !cur().locked ? "inline-flex" : "none" }}><IcTrash size={13} /> Xóa đoạn</button>
467
  <span className="small muted">{cur() && cur().locked ? "🔒 text lồng tiếng — không xóa được" : ""}</span>
 
47
  let t = start; return words.map((w, i) => { const wd = dur * wt[i] / tot; const o = { w, start: t, end: t + wd }; t += wd; return o; });
48
  };
49
 
50
+ export default function SubtitleEditor({
51
+ session, videoUrl, videoRel, srtRel, username, onClose,
52
+ // ---- Chế độ dùng lại cho tab "Chèn chữ vào video" (nhiều video) ----
53
+ initialSegs = null, // segs khởi tạo (khôi phục khi chuyển qua lại video)
54
+ initialMode = null, // mode khởi tạo
55
+ onChange = null, // (segs, mode, payload) -> đẩy state lên cha để lưu/áp form
56
+ headerExtra = null, // JSX chèn thêm ở header (vd nút "Áp form cho mọi video")
57
+ onFetchLines = null, // async () -> [{start,end,text}] : nhận dạng lời từ video (ASR)
58
+ }) {
59
+ // Nhân bản sâu segs khởi tạo -> không dùng chung tham chiếu với state cha.
60
+ const [segs, setSegs] = useState(() =>
61
+ initialSegs ? JSON.parse(JSON.stringify(initialSegs)) : []);
62
  const [sel, setSel] = useState(0);
63
+ const [mode, setMode] = useState(initialMode || "whole");
64
  const [playing, setPlaying] = useState(false);
65
  const [t, setT] = useState(0);
66
  const [dur, setDur] = useState(0);
 
91
  const pollAbort = useRef(new AbortController());
92
  useEffect(() => () => pollAbort.current.abort(), []);
93
 
94
+ // Nhận dạng LỜI GỐC trong video (ASR) -> đổ vào editor thành các đoạn chữ SỬA
95
+ // ĐƯỢC (không khoá), để user tạo kiểu & burn. Dùng ở tab "Chèn chữ vào video".
96
+ const [fetchingLines, setFetchingLines] = useState(false);
97
+ const loadLines = async () => {
98
+ if (!onFetchLines) return;
99
+ if (segs.some((s) => !s.locked) &&
100
+ !window.confirm("Thay các đoạn chữ đang có bằng lời nhận dạng từ video?")) return;
101
+ setFetchingLines(true);
102
+ try {
103
+ const lines = await onFetchLines();
104
+ const loaded = (lines || []).map((s) => ({
105
+ start: +s.start, end: +s.end, text: s.text || "", locked: false,
106
+ words: wordsFor(s.text, s.start, s.end),
107
+ style: JSON.parse(JSON.stringify(DEF)),
108
+ }));
109
+ if (!loaded.length) { alert("Không nhận được lời nào từ video (có thể video không có tiếng nói)."); return; }
110
+ setSegs((cur) => [...cur.filter((x) => x.locked), ...loaded]);
111
+ setSel(0);
112
+ } catch (e) { alert("Lỗi nhận dạng lời: " + (e?.message || e)); }
113
+ finally { setFetchingLines(false); }
114
+ };
115
+
116
  // Tự sinh phụ đề từ lời dịch (SRT). User bấm nút này khi muốn.
117
  const autoSubtitle = async () => {
118
  try {
 
279
  start: s.start, end: s.end, text: s.text, style: s.style, breaks: measureBreaks(s),
280
  }));
281
 
282
+ // Đẩy state (segs + mode + payload đã đo breaks) lên component cha khi có onChange
283
+ // (tab "Chèn chữ nhiều video"): cha lưu theo từng video + để "áp form cho mọi video".
284
+ // payload đo breaks bằng ĐÚNG video đang mở -> burn hàng loạt khớp bản xem trước.
285
+ useEffect(() => {
286
+ if (!onChange) return;
287
+ try { onChange(segs, mode, segPayload()); }
288
+ catch { onChange(segs, mode, null); }
289
+ // eslint-disable-next-line
290
+ }, [segs, mode]);
291
+
292
  const burn = async () => {
293
  if (!segs.length) return alert("Chưa có đoạn text nào. Bấm 'Tự tạo phụ đề' hoặc 'Thêm text'.");
294
  setBusy(true); setResult(null);
 
407
 
408
  return (
409
  <div className="card" style={{ borderColor: "var(--orange)" }}>
410
+ <div className="flex between center" style={{ gap: 8, flexWrap: "wrap" }}>
411
+ <div className="panel-title" style={{ margin: 0 }}>Chèn chữ / phụ đề (hard sub)</div>
412
+ <div className="flex center gap8" style={{ flexWrap: "wrap" }}>
413
+ {headerExtra}
414
+ {onClose && <button className="btn sm ghost" onClick={onClose}>Đóng</button>}
415
+ </div>
416
  </div>
417
 
418
  <div className="grid-2" style={{ gridTemplateColumns: "300px 1fr", gap: 16, marginTop: 10 }}>
 
504
 
505
  {/* controls */}
506
  <div className="stack" style={{ gap: 12 }}>
507
+ {srtRel && segs.filter((s) => s.locked).length === 0 && (
508
  <button className="btn primary" onClick={autoSubtitle}>Tự tạo phụ đề từ lời dịch</button>
509
  )}
510
+ {onFetchLines && (
511
+ <button className="btn primary" onClick={loadLines} disabled={fetchingLines}
512
+ title="Nhận dạng lời thoại trong video (Whisper) và đổ sẵn vào để sửa">
513
+ {fetchingLines ? "Đang nhận dạng lời…" : "🎙 Tự lấy lời từ video (nhận dạng)"}
514
+ </button>
515
+ )}
516
  <div className="flex gap8 center">
517
  <button className="btn sm ghost" onClick={delText} style={{ display: cur() && !cur().locked ? "inline-flex" : "none" }}><IcTrash size={13} /> Xóa đoạn</button>
518
  <span className="small muted">{cur() && cur().locked ? "🔒 text lồng tiếng — không xóa được" : ""}</span>
frontend/src/pages/TextVideo.jsx ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { api, pollJob, fileUrl } from "../api";
3
+ import { useToolState } from "../store";
4
+ import { useAuth } from "../stores/authStore";
5
+ import { ProcessRail, FileDrop, ProcessingOverlay, CacheNote } from "../components/ui";
6
+ import { IcText, IcDownload, IcVideo } from "../components/Icons";
7
+ import SubtitleEditor from "../components/SubtitleEditor";
8
+
9
+ const STEPS = [
10
+ { t: "Tải video", d: "Tải 1 hoặc nhiều video cần chèn chữ." },
11
+ { t: "Lấy lời & tạo kiểu chữ", d: "Tự nhận dạng lời trong video (hoặc gõ tay), chọn phông/màu/nền, kéo đặt vị trí." },
12
+ { t: "Áp form cho mọi video", d: "Làm 1 video rồi áp cùng kiểu (và cả lời nếu muốn) cho các video còn lại." },
13
+ { t: "Tạo tất cả", d: "Burn chữ vào từng video — vào bao nhiêu ra bấy nhiêu." },
14
+ ];
15
+
16
+ const clone = (x) => JSON.parse(JSON.stringify(x));
17
+
18
+ export default function TextVideo() {
19
+ const { user } = useAuth();
20
+ const [st, set] = useToolState("textvid", {
21
+ session: null,
22
+ videos: [], // [{file,name,size,url}]
23
+ selIdx: 0, // video đang mở trong trình chèn chữ (-1 = chưa mở)
24
+ forms: {}, // { [file]: {segs, mode, payload} } — chữ của từng video
25
+ outputs: [], // [{name, video_url, srcName, srcUrl}]
26
+ outStamp: 0,
27
+ busy: false, job: null,
28
+ });
29
+ const [showNote, setShowNote] = useState(true);
30
+ const [uploading, setUploading] = useState(null); // {name,i,n}
31
+ const [msg, setMsg] = useState(""); // báo nhẹ sau khi áp form
32
+ const busy = st.busy;
33
+ const job = st.job;
34
+ const setBusy = (b) => set({ busy: b });
35
+ const setJob = (j) => set({ job: j });
36
+ const pollAbort = useRef(new AbortController());
37
+ useEffect(() => () => pollAbort.current.abort(), []);
38
+ useEffect(() => {
39
+ if (!msg) return;
40
+ const t = setTimeout(() => setMsg(""), 4000);
41
+ return () => clearTimeout(t);
42
+ }, [msg]);
43
+
44
+ const addVideos = async (files) => {
45
+ let sid = st.session;
46
+ const added = [];
47
+ const arr = Array.from(files);
48
+ for (let i = 0; i < arr.length; i++) {
49
+ const file = arr[i];
50
+ setUploading({ name: file.name, i: i + 1, n: arr.length });
51
+ try {
52
+ const r = await api.dubUpload(file, sid);
53
+ sid = r.session;
54
+ added.push({ file: r.file, name: r.name, size: r.size, url: `/api/files/${sid}/${r.file}` });
55
+ } catch (e) { alert("Lỗi tải video: " + e.message); }
56
+ }
57
+ setUploading(null);
58
+ set((cur) => ({
59
+ session: sid,
60
+ videos: [...cur.videos, ...added],
61
+ // nếu chưa mở video nào -> mở video đầu tiên vừa thêm
62
+ selIdx: cur.selIdx < 0 || !cur.videos.length ? cur.videos.length : cur.selIdx,
63
+ }));
64
+ };
65
+
66
+ const removeVideo = (i) => set((cur) => {
67
+ const v = cur.videos[i];
68
+ const forms = { ...cur.forms };
69
+ if (v) delete forms[v.file];
70
+ const videos = cur.videos.filter((_, j) => j !== i);
71
+ let selIdx = cur.selIdx;
72
+ if (selIdx === i) selIdx = videos.length ? Math.min(i, videos.length - 1) : -1;
73
+ else if (selIdx > i) selIdx -= 1;
74
+ return { videos, forms, selIdx };
75
+ });
76
+
77
+ // Lưu chữ của video đang mở (editor gọi mỗi khi segs/mode đổi).
78
+ const onEditorChange = (file) => (segs, mode, payload) =>
79
+ set((cur) => ({ forms: { ...cur.forms, [file]: { segs, mode, payload } } }));
80
+
81
+ // Áp FORM chữ (segs + kiểu + vị trí) của video đang mở cho MỌI video còn lại —
82
+ // để hàng loạt video quảng cáo cùng chiến dịch có chữ giống hệt nhau.
83
+ const applyFormAll = () => {
84
+ const curV = st.videos[st.selIdx];
85
+ if (!curV) return;
86
+ const f = st.forms[curV.file];
87
+ if (!f || !(f.segs || []).length) { setMsg("⚠ Video này chưa có chữ để áp."); return; }
88
+ let count = 0;
89
+ set((cur) => {
90
+ const forms = { ...cur.forms };
91
+ for (const v of cur.videos) {
92
+ if (v.file === curV.file) continue;
93
+ forms[v.file] = { segs: clone(f.segs), mode: f.mode, payload: clone(f.payload || []) };
94
+ count++;
95
+ }
96
+ return { forms };
97
+ });
98
+ setMsg(count > 0
99
+ ? `✅ Đã áp form chữ cho ${count} video khác (cùng kiểu, cùng vị trí).`
100
+ : "Không có video nào khác để áp.");
101
+ };
102
+
103
+ // Áp KIỂU CHỮ (phông/màu/nền/cỡ/vị trí) của video đang mở cho MỌI video còn lại,
104
+ // NHƯNG GIỮ NGUYÊN lời riêng của từng video. Hợp khi mỗi video tự nhận dạng lời
105
+ // khác nhau mà vẫn muốn nhìn giống nhau. Template = kiểu của đoạn đầu video đang mở.
106
+ const applyStyleAll = () => {
107
+ const curV = st.videos[st.selIdx];
108
+ if (!curV) return;
109
+ const f = st.forms[curV.file];
110
+ const tmpl = f?.segs?.[0]?.style;
111
+ if (!tmpl) { setMsg("⚠ Video này chưa có chữ để lấy kiểu."); return; }
112
+ let count = 0;
113
+ set((cur) => {
114
+ const forms = { ...cur.forms };
115
+ for (const v of cur.videos) {
116
+ if (v.file === curV.file) continue;
117
+ const g = forms[v.file];
118
+ if (!g || !(g.segs || []).length) continue; // video chưa có chữ -> bỏ qua
119
+ const segs = g.segs.map((s) => ({ ...s, style: clone(tmpl) }));
120
+ forms[v.file] = { ...g, segs, payload: (g.payload || []).map((p) => ({ ...p, style: clone(tmpl) })) };
121
+ count++;
122
+ }
123
+ return { forms };
124
+ });
125
+ setMsg(count > 0
126
+ ? `✅ Đã áp KIỂU chữ cho ${count} video (giữ lời riêng từng video).`
127
+ : "Không có video nào khác đang có chữ để áp kiểu.");
128
+ };
129
+
130
+ // Nhận dạng lời gốc trong video đang mở (ASR) -> trả lines cho editor đổ vào.
131
+ const fetchLines = async () => {
132
+ if (!selV) return [];
133
+ setBusy(true);
134
+ try {
135
+ const { job_id } = await api.dubTranscribe({ session: st.session, video: selV.file });
136
+ const done = await pollJob(job_id, setJob, 1000, pollAbort.current.signal);
137
+ const out = done.result?.output ||
138
+ (done.items || []).find((i) => i.status === "done")?.result;
139
+ if (done.status === "error" || !out)
140
+ throw new Error(done.items?.[0]?.error || done.error || "Không nhận dạng được lời");
141
+ return out.lines || [];
142
+ } finally { setBusy(false); }
143
+ };
144
+
145
+ // Burn chữ vào TẤT CẢ video có chữ -> mỗi video 1 kết quả (vào bao nhiêu ra bấy nhiêu).
146
+ const burnAll = async () => {
147
+ const targets = st.videos.filter((v) => (st.forms[v.file]?.payload || []).length);
148
+ if (!targets.length) {
149
+ alert("Chưa video nào có chữ. Mở video, thêm chữ (hoặc bấm “Áp form cho mọi video”).");
150
+ return;
151
+ }
152
+ setBusy(true); set({ outputs: [] });
153
+ const outs = [];
154
+ try {
155
+ for (const v of targets) {
156
+ const f = st.forms[v.file];
157
+ const { job_id } = await api.subtitleBurn({
158
+ session: st.session, video: v.file, mode: f.mode || "whole",
159
+ segments: f.payload, username: user || "",
160
+ });
161
+ const done = await pollJob(job_id, setJob, 1000, pollAbort.current.signal);
162
+ const out = done.result?.output ||
163
+ (done.items || []).find((i) => i.status === "done")?.result;
164
+ if (out) outs.push({ ...out, srcName: v.name, srcUrl: v.url });
165
+ }
166
+ set({ outputs: outs, outStamp: Date.now() });
167
+ if (!outs.length) alert("Không tạo được video nào (xem log).");
168
+ } catch (e) { alert("Lỗi: " + e.message); }
169
+ finally { setBusy(false); }
170
+ };
171
+
172
+ const startNew = () => {
173
+ if (busy) return;
174
+ if (!st.videos.length && !st.outputs.length) return;
175
+ if (!window.confirm("Xoá video & kết quả hiện tại để làm mẻ khác?")) return;
176
+ set({ videos: [], forms: {}, outputs: [], selIdx: -1, job: null, outStamp: 0 });
177
+ };
178
+
179
+ const nText = (file) => (st.forms[file]?.segs || []).length;
180
+ const selV = st.selIdx >= 0 ? st.videos[st.selIdx] : null;
181
+ const nWithText = st.videos.filter((v) => nText(v.file) > 0).length;
182
+
183
+ const vidStyle = { display: "block", margin: "0 auto", maxWidth: "100%", maxHeight: 360, width: "auto", borderRadius: 10 };
184
+
185
+ return (
186
+ <div>
187
+ <div className="h1"><IcText size={22} /> Workspace: <span className="accent">Chèn chữ vào video</span></div>
188
+ <p className="subtitle">Đầu vào 1 hoặc nhiều video, tự nhận dạng lời trong video (hoặc gõ tay), chèn chữ (đủ kiểu phông/màu/nền/hiển thị), làm 1 video rồi áp form cho tất cả. Vào bao nhiêu ra bấy nhiêu.</p>
189
+ {showNote && <CacheNote onClose={() => setShowNote(false)} />}
190
+
191
+ <div className="grid-2">
192
+ <div className="stack">
193
+ {/* 1. upload */}
194
+ <div className="card">
195
+ <div className="panel-title">1. Tải lên video cần chèn chữ</div>
196
+ <FileDrop onFiles={addVideos} hint="MP4, MOV, AVI, MKV · có thể chọn nhiều video" />
197
+ {uploading && (
198
+ <div className="small mt8" style={{ color: "var(--orange-700)" }}>
199
+ ⏳ Đang tải lên: <b>{uploading.name}</b> ({uploading.i}/{uploading.n})…
200
+ </div>
201
+ )}
202
+ {st.videos.length > 0 && (
203
+ <>
204
+ <div className="small muted mt12" style={{ marginBottom: 6 }}>
205
+ {st.videos.length} video · {nWithText} video đã có chữ. Bấm để mở/chèn chữ:
206
+ </div>
207
+ <div className="filelist">
208
+ {st.videos.map((v, i) => (
209
+ <div className="filerow" key={v.file}
210
+ style={{ cursor: "pointer", borderColor: i === st.selIdx ? "var(--orange)" : undefined, background: i === st.selIdx ? "var(--orange-soft)" : undefined }}
211
+ onClick={() => set({ selIdx: i })}>
212
+ <div style={{ flex: 1, minWidth: 0 }}>
213
+ <div className="fn">{i === st.selIdx ? "✏ " : ""}{v.name}</div>
214
+ <div className="meta">
215
+ {(v.size / 1048576).toFixed(1)} MB
216
+ {nText(v.file) > 0 && <span style={{ color: "var(--green)", fontWeight: 600 }}> · {nText(v.file)} đoạn chữ</span>}
217
+ </div>
218
+ </div>
219
+ <button className="x" onClick={(e) => { e.stopPropagation(); removeVideo(i); }} title="Xoá">✕</button>
220
+ </div>
221
+ ))}
222
+ </div>
223
+ </>
224
+ )}
225
+ </div>
226
+
227
+ <ProcessingOverlay busy={busy} job={job} title="Đang chèn chữ vào video…" />
228
+
229
+ {/* 2. trình chèn chữ cho video đang chọn */}
230
+ {selV ? (
231
+ <SubtitleEditor
232
+ key={selV.file}
233
+ session={st.session}
234
+ videoUrl={fileUrl(selV.url)}
235
+ videoRel={selV.file}
236
+ username={user}
237
+ initialSegs={st.forms[selV.file]?.segs || null}
238
+ initialMode={st.forms[selV.file]?.mode || null}
239
+ onChange={onEditorChange(selV.file)}
240
+ onFetchLines={fetchLines}
241
+ onClose={null}
242
+ headerExtra={
243
+ <>
244
+ <span className="small muted" style={{ maxWidth: 200 }}>{selV.name}</span>
245
+ {st.videos.length > 1 && (
246
+ <>
247
+ <button className="btn sm" onClick={applyFormAll}
248
+ title="Áp CẢ lời + kiểu + vị trí của video này cho MỌI video còn lại (khi mọi video cùng nội dung)">
249
+ ⇊ Áp cả lời + kiểu
250
+ </button>
251
+ <button className="btn sm" onClick={applyStyleAll}
252
+ title="Chỉ áp KIỂU chữ (phông/màu/nền/vị trí), GIỮ lời riêng của từng video (khi mỗi video tự nhận dạng lời khác nhau)">
253
+ 🎨 Áp kiểu (giữ lời riêng)
254
+ </button>
255
+ </>
256
+ )}
257
+ </>
258
+ }
259
+ />
260
+ ) : st.videos.length > 0 ? (
261
+ <div className="card"><div className="small muted">Chọn một video ở trên để bắt đầu chèn chữ.</div></div>
262
+ ) : null}
263
+
264
+ {msg && (
265
+ <div className="small" style={{
266
+ padding: "8px 12px", borderRadius: 8,
267
+ background: "var(--green-soft)", color: "var(--green)", fontWeight: 600,
268
+ }}>{msg}</div>
269
+ )}
270
+
271
+ {/* 3. tạo tất cả */}
272
+ {st.videos.length > 0 && (
273
+ <div className="card">
274
+ <div className="panel-title">Tạo video</div>
275
+ <p className="small muted" style={{ marginTop: -6 }}>
276
+ Burn chữ vào <b>{nWithText}</b> video có chữ. Mỗi video vào → một video ra.
277
+ {st.videos.length > 1 && " Muốn mọi video giống nhau: chèn chữ 1 video rồi bấm “Áp form cho mọi video”."}
278
+ </p>
279
+ <button className="btn primary block mt8" onClick={burnAll} disabled={busy || !nWithText}>
280
+ {busy ? "Đang tạo video…" : <><IcVideo size={16} /> Tạo tất cả video có chữ ({nWithText})</>}
281
+ </button>
282
+ </div>
283
+ )}
284
+
285
+ {/* kết quả */}
286
+ {st.outputs.length > 0 && (
287
+ <div className="card">
288
+ <div className="flex between center" style={{ marginBottom: 10, gap: 8, flexWrap: "wrap" }}>
289
+ <div className="panel-title" style={{ margin: 0 }}>Kết quả ({st.outputs.length})</div>
290
+ <button className="btn sm primary" onClick={startNew} disabled={busy}
291
+ title="Xoá video & kết quả hiện tại để làm mẻ khác (không cần tải lại trang)">
292
+ + Làm mẻ mới
293
+ </button>
294
+ </div>
295
+ <div className="stack">
296
+ {st.outputs.map((o) => {
297
+ const bust = st.outStamp ? `?v=${st.outStamp}` : "";
298
+ return (
299
+ <div key={o.video_url} style={{ border: "1px solid var(--line)", borderRadius: 12, padding: 14 }}>
300
+ <div className="flex between center" style={{ marginBottom: 10 }}>
301
+ <b className="small">{o.srcName}</b>
302
+ <span className="badge done"><span className="dot" /> đã chèn chữ</span>
303
+ </div>
304
+ <div className="row wrap">
305
+ {o.srcUrl && (
306
+ <div style={{ flex: 1, minWidth: 220 }}>
307
+ <div className="small muted" style={{ marginBottom: 6 }}>Trước (gốc)</div>
308
+ <video src={fileUrl(o.srcUrl)} controls style={vidStyle} />
309
+ </div>
310
+ )}
311
+ <div style={{ flex: 1, minWidth: 220 }}>
312
+ <div className="small muted" style={{ marginBottom: 6 }}>Sau (đã chèn chữ)</div>
313
+ <video key={fileUrl(o.video_url) + bust} src={fileUrl(o.video_url) + bust} controls style={vidStyle} />
314
+ </div>
315
+ </div>
316
+ <div className="flex gap8 mt12" style={{ flexWrap: "wrap" }}>
317
+ <a className="btn sm" href={fileUrl(o.video_url)} download><IcDownload size={14} /> Tải video MP4</a>
318
+ </div>
319
+ </div>
320
+ );
321
+ })}
322
+ </div>
323
+ </div>
324
+ )}
325
+ </div>
326
+
327
+ <ProcessRail steps={STEPS} tip="Chèn chữ dùng chung bộ công cụ với “Dịch / đổi giọng”: đủ phông tiếng Việt, 11 kiểu nền, 3 kiểu hiển thị (cả câu / hiện dần / highlight). Kéo tay trái–phải đổi bề rộng, trên–dưới đổi cỡ chữ. Xem trước khớp 100% khi tạm dừng." />
328
+ </div>
329
+ </div>
330
+ );
331
+ }