titusgiap commited on
Commit
c55989f
·
1 Parent(s): 1bab57c

update add subtitle

Browse files
backend/app/api/cut.py CHANGED
@@ -41,7 +41,7 @@ async def upload(file: UploadFile = File(...), session: str = Form(None)):
41
  class PreviewReq(BaseModel):
42
  session: str
43
  file: str
44
- mode: str = "even" # even | scene | highlight | smart
45
  count: int | None = None # số khúc (even) — None để máy tự chia
46
  min_len: float = 1.5
47
  sensitivity: float = 0.5
@@ -51,15 +51,19 @@ class PreviewReq(BaseModel):
51
 
52
  @router.post("/preview")
53
  def preview(req: PreviewReq):
 
54
  src = os.path.join(session_dir(req.session), req.file)
55
  info = probe(src)
56
  segs = modes.build_segments(
57
  info, req.mode, n=req.count, min_len=req.min_len,
58
  sensitivity=req.sensitivity, top_ratio=req.top_ratio)
 
 
 
59
  thumbs = cutter.thumbnail_strip(
60
- info, sub_dir(req.session, "thumbs"), count=req.thumbnails)
61
  rel_thumbs = [{"time": t["time"],
62
- "url": f"/api/files/{req.session}/thumbs/{os.path.basename(t['path'])}"}
63
  for t in thumbs]
64
  return {
65
  "info": {"duration": info.duration, "fps": info.fps,
@@ -79,7 +83,7 @@ class ExecuteReq(BaseModel):
79
  file: str
80
  # điểm cắt cuối cùng (đã chỉnh tay / thêm khúc trong UI). Nếu rỗng -> dùng mode.
81
  segments: list[CutPoint] | None = None
82
- mode: str = "even"
83
  count: int | None = None
84
 
85
 
@@ -124,7 +128,7 @@ def execute(req: ExecuteReq):
124
  class BatchItem(BaseModel):
125
  file: str
126
  segments: list[CutPoint] | None = None
127
- mode: str = "even"
128
  count: int | None = None
129
 
130
 
 
41
  class PreviewReq(BaseModel):
42
  session: str
43
  file: str
44
+ mode: str = "smart" # smart | highlight | scene | even
45
  count: int | None = None # số khúc (even) — None để máy tự chia
46
  min_len: float = 1.5
47
  sensitivity: float = 0.5
 
51
 
52
  @router.post("/preview")
53
  def preview(req: PreviewReq):
54
+ import hashlib
55
  src = os.path.join(session_dir(req.session), req.file)
56
  info = probe(src)
57
  segs = modes.build_segments(
58
  info, req.mode, n=req.count, min_len=req.min_len,
59
  sensitivity=req.sensitivity, top_ratio=req.top_ratio)
60
+ # Mỗi video có thư mục thumbnail RIÊNG (theo hash đường dẫn file) để nhiều
61
+ # video trong cùng phiên KHÔNG ghi đè thumbnail của nhau (thumb_000.jpg...).
62
+ vkey = hashlib.md5(req.file.encode("utf-8")).hexdigest()[:8]
63
  thumbs = cutter.thumbnail_strip(
64
+ info, sub_dir(req.session, "thumbs", vkey), count=req.thumbnails)
65
  rel_thumbs = [{"time": t["time"],
66
+ "url": f"/api/files/{req.session}/thumbs/{vkey}/{os.path.basename(t['path'])}"}
67
  for t in thumbs]
68
  return {
69
  "info": {"duration": info.duration, "fps": info.fps,
 
83
  file: str
84
  # điểm cắt cuối cùng (đã chỉnh tay / thêm khúc trong UI). Nếu rỗng -> dùng mode.
85
  segments: list[CutPoint] | None = None
86
+ mode: str = "smart"
87
  count: int | None = None
88
 
89
 
 
128
  class BatchItem(BaseModel):
129
  file: str
130
  segments: list[CutPoint] | None = None
131
+ mode: str = "smart"
132
  count: int | None = None
133
 
134
 
backend/app/api/dub.py CHANGED
@@ -233,3 +233,78 @@ def tts_from_text(req: TtsReq):
233
 
234
  jobs.submit(job, work)
235
  return {"job_id": job.id, "session": sid}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  jobs.submit(job, work)
235
  return {"job_id": job.id, "session": sid}
236
+
237
+
238
+ # --------------------------------------------------- HARD SUBTITLE ---
239
+
240
+ class SubPlanReq(BaseModel):
241
+ session: str
242
+ srt: str # rel path file SRT (từ kết quả dịch)
243
+ max_words: int = 7
244
+ max_dur: float = 3.6
245
+
246
+
247
+ @router.post("/subtitle/plan")
248
+ def subtitle_plan(req: SubPlanReq):
249
+ """Tự sinh danh sách ĐOẠN phụ đề (tách câu dài + mốc từng từ) để FE dựng editor."""
250
+ from ..services.dubber import subtitle_render as sub
251
+ path = os.path.join(session_dir(req.session), req.srt)
252
+ if not os.path.exists(path):
253
+ return {"segments": []}
254
+ lines = sub.parse_srt(path)
255
+ segs = sub.split_lines(lines, req.max_words, req.max_dur)
256
+ return {"segments": segs}
257
+
258
+
259
+ class SubSegIn(BaseModel):
260
+ start: float
261
+ end: float
262
+ text: str
263
+ style: dict = {} # {font,fontSize,color,highlight,bg,x,y,w}
264
+ breaks: list[int] = [] # index từ bắt đầu dòng mới (FE đo chữ thật)
265
+
266
+
267
+ class SubBurnReq(BaseModel):
268
+ session: str
269
+ video: str # rel path video đã dịch cần chèn phụ đề
270
+ segments: list[SubSegIn]
271
+ mode: str = "whole" # whole | progressive | highlight
272
+ username: str = ""
273
+
274
+
275
+ @router.post("/subtitle")
276
+ def subtitle_burn(req: SubBurnReq):
277
+ """Burn cứng phụ đề (theo style/vị trí từng đoạn) vào video."""
278
+ from ..services.dubber import subtitle_render as sub
279
+ job = jobs.create("subtitle")
280
+
281
+ def work(h):
282
+ it = h.add_item("subtitle")
283
+ try:
284
+ h.item_status(it, "running", detail="Chuẩn bị phụ đề")
285
+ vid = os.path.join(session_dir(req.session), req.video)
286
+ res = sub.probe_size(vid)
287
+ segs = []
288
+ for s in req.segments:
289
+ segs.append({"start": s.start, "end": s.end, "text": s.text,
290
+ "style": s.style, "breaks": s.breaks,
291
+ "words": sub.words_for(s.text, s.start, s.end)})
292
+ out_dir = sub_dir(req.session, "subtitled")
293
+ ass = os.path.join(out_dir, "sub.ass")
294
+ sub.build_ass(segs, ass, mode=req.mode, res=res)
295
+ h.item_status(it, "running", detail="Đang burn phụ đề (ffmpeg)")
296
+ h.set_progress(0.3)
297
+ name = "video_subtitled.mp4"
298
+ out = os.path.join(out_dir, name)
299
+ sub.burn(vid, ass, out)
300
+ result = {"name": name,
301
+ "video_url": f"/api/files/{req.session}/subtitled/{name}"}
302
+ h.item_status(it, "done", detail="xong", result=result)
303
+ h.set_progress(1.0)
304
+ return {"session": req.session, "output": result}
305
+ except Exception as e:
306
+ h.item_status(it, "error", error=str(e))
307
+ return {"session": req.session, "error": str(e)}
308
+
309
+ jobs.submit(job, work)
310
+ return {"job_id": job.id, "session": req.session}
backend/app/services/downloader/ydl.py CHANGED
@@ -109,18 +109,41 @@ def _has_video_stream(path: str) -> bool:
109
  return False
110
 
111
 
112
- def _build_opts(out_dir: str, cookies_file: str | None, generic: bool = False) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  opts = {
114
  "outtmpl": os.path.join(out_dir, "%(title).80s [%(id)s].%(ext)s"),
115
- "format": "bv*+ba/b/best",
116
  "merge_output_format": "mp4",
117
  "postprocessors": [{"key": "FFmpegVideoRemuxer", "preferedformat": "mp4"}],
118
  "noplaylist": True,
119
  "quiet": True,
120
  "no_warnings": True,
121
  "retries": 3,
 
122
  "concurrent_fragment_downloads": 4,
123
  "writethumbnail": False,
 
124
  }
125
  if generic:
126
  # thử quét video nhúng trong trang (Shopee/1688/Taobao... không có extractor riêng)
@@ -154,6 +177,68 @@ def _attempt(url: str, out_dir: str, opts: dict) -> DownloadResult:
154
  )
155
 
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> DownloadResult:
158
  try:
159
  import yt_dlp # noqa: F401 # type: ignore
@@ -164,14 +249,32 @@ def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> Dow
164
  os.makedirs(out_dir, exist_ok=True)
165
  url = normalize_url(url)
166
  source = detect_source(url)
 
 
 
 
 
 
 
 
 
 
167
  try:
168
- return _attempt(url, out_dir, _build_opts(out_dir, cookies_file))
169
  except Exception as e: # pragma: no cover - lỗi mạng/extractor
170
  first_err = clean_error(e)
 
 
 
 
 
 
 
171
  # Shopee/1688/Taobao: thử lại bằng generic extractor (quét video trong trang)
172
  if source in ("shopee", "1688", "taobao"):
173
  try:
174
- return _attempt(url, out_dir, _build_opts(out_dir, cookies_file, generic=True))
 
175
  except Exception as e2:
176
  return DownloadResult(url=url, ok=False,
177
  error=clean_error(f"{source}: {e2}"))
 
109
  return False
110
 
111
 
112
+ # Trình duyệt giả để nhiều site (Douyin/TikTok...) không chặn request như bot.
113
+ _UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
114
+ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
115
+
116
+ # Referer theo nguồn — chống anti-hotlink (Douyin đặc biệt cần cái này).
117
+ _REFERER = {
118
+ "douyin": "https://www.douyin.com/",
119
+ "tiktok": "https://www.tiktok.com/",
120
+ "facebook": "https://www.facebook.com/",
121
+ "instagram": "https://www.instagram.com/",
122
+ "youtube": "https://www.youtube.com/",
123
+ }
124
+
125
+
126
+ def _build_opts(out_dir: str, cookies_file: str | None = None,
127
+ generic: bool = False, source: str = "",
128
+ fmt: str | None = None) -> dict:
129
+ # Header trình duyệt + Referer theo nguồn -> tải được Douyin/TikTok KHÔNG cần cookies.
130
+ headers = {"User-Agent": _UA}
131
+ ref = _REFERER.get(source)
132
+ if ref:
133
+ headers["Referer"] = ref
134
  opts = {
135
  "outtmpl": os.path.join(out_dir, "%(title).80s [%(id)s].%(ext)s"),
136
+ "format": fmt or "bv*+ba/b/best",
137
  "merge_output_format": "mp4",
138
  "postprocessors": [{"key": "FFmpegVideoRemuxer", "preferedformat": "mp4"}],
139
  "noplaylist": True,
140
  "quiet": True,
141
  "no_warnings": True,
142
  "retries": 3,
143
+ "extractor_retries": 3,
144
  "concurrent_fragment_downloads": 4,
145
  "writethumbnail": False,
146
+ "http_headers": headers,
147
  }
148
  if generic:
149
  # thử quét video nhúng trong trang (Shopee/1688/Taobao... không có extractor riêng)
 
177
  )
178
 
179
 
180
+ _UA_MOBILE = ("Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) "
181
+ "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 "
182
+ "Mobile/15E148 Safari/604.1")
183
+
184
+
185
+ def _douyin_direct(url: str, out_dir: str) -> DownloadResult:
186
+ """Tải Douyin KHÔNG cần cookies.
187
+
188
+ Extractor Douyin của yt-dlp nay đòi 'fresh cookies'. Thay vào đó ta lấy trang
189
+ chia sẻ iesdouyin (bản mobile), bóc link video từ JSON `_ROUTER_DATA` rồi tải
190
+ thẳng. Đổi 'playwm' -> 'play' để lấy bản không watermark.
191
+ """
192
+ import json
193
+ import re as _re
194
+ import requests # type: ignore
195
+
196
+ m = _re.search(r"/video/(\d+)", url) or _re.search(r"modal_id=(\d+)", url)
197
+ if not m:
198
+ raise RuntimeError("không tìm được id video douyin")
199
+ vid = m.group(1)
200
+ s = requests.Session()
201
+ s.headers.update({"User-Agent": _UA_MOBILE})
202
+ r = s.get(f"https://www.iesdouyin.com/share/video/{vid}/", timeout=25)
203
+ mm = _re.search(r"window\._ROUTER_DATA\s*=\s*(\{.*?\})\s*</script>", r.text, _re.S)
204
+ if not mm:
205
+ raise RuntimeError("không đọc được dữ liệu trang share douyin")
206
+ data = json.loads(mm.group(1))
207
+ urls: list[str] = []
208
+ title = {"v": ""}
209
+
210
+ def walk(o):
211
+ if isinstance(o, dict):
212
+ pa = o.get("play_addr")
213
+ if isinstance(pa, dict):
214
+ urls.extend(pa.get("url_list", []))
215
+ if not title["v"] and isinstance(o.get("desc"), str):
216
+ title["v"] = o["desc"]
217
+ for v in o.values():
218
+ walk(v)
219
+ elif isinstance(o, list):
220
+ for v in o:
221
+ walk(v)
222
+
223
+ walk(data)
224
+ play = [u if u.startswith("http") else "https:" + u for u in urls]
225
+ if not play:
226
+ raise RuntimeError("không có link video (có thể là bài ảnh/slideshow)")
227
+ src_url = play[0].replace("playwm", "play")
228
+ vr = s.get(src_url, timeout=60, headers={"Referer": "https://www.douyin.com/"})
229
+ vr.raise_for_status()
230
+ ttl = (title["v"] or vid).strip()
231
+ safe = re.sub(r'[\\/:*?"<>|\n\r\t]+', "_", ttl)[:60].strip() or vid
232
+ path = os.path.join(out_dir, f"{safe} [{vid}].mp4")
233
+ with open(path, "wb") as f:
234
+ f.write(vr.content)
235
+ if not _has_video_stream(path):
236
+ raise RuntimeError("file tải về không phải video xem được")
237
+ return DownloadResult(
238
+ url=url, ok=True, path=path, title=ttl, ext="mp4",
239
+ size=os.path.getsize(path), duration=0.0, thumbnail="")
240
+
241
+
242
  def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> DownloadResult:
243
  try:
244
  import yt_dlp # noqa: F401 # type: ignore
 
249
  os.makedirs(out_dir, exist_ok=True)
250
  url = normalize_url(url)
251
  source = detect_source(url)
252
+ # Douyin: dùng cách bóc link trực tiếp (không cookies) TRƯỚC; yt-dlp là dự phòng.
253
+ if source == "douyin":
254
+ try:
255
+ return _douyin_direct(url, out_dir)
256
+ except Exception as e_d:
257
+ try:
258
+ return _attempt(url, out_dir, _build_opts(out_dir, cookies_file, source=source))
259
+ except Exception:
260
+ return DownloadResult(url=url, ok=False,
261
+ error=clean_error(f"douyin: {e_d}"))
262
  try:
263
+ return _attempt(url, out_dir, _build_opts(out_dir, cookies_file, source=source))
264
  except Exception as e: # pragma: no cover - lỗi mạng/extractor
265
  first_err = clean_error(e)
266
+ # Thử lại với format đơn giản "best" — nhiều nguồn (Douyin) không có luồng
267
+ # video/âm thanh tách rời nên "bv*+ba" fail, "best" (file gộp sẵn) lại chạy.
268
+ try:
269
+ return _attempt(url, out_dir,
270
+ _build_opts(out_dir, cookies_file, source=source, fmt="best"))
271
+ except Exception:
272
+ pass
273
  # Shopee/1688/Taobao: thử lại bằng generic extractor (quét video trong trang)
274
  if source in ("shopee", "1688", "taobao"):
275
  try:
276
+ return _attempt(url, out_dir,
277
+ _build_opts(out_dir, cookies_file, generic=True, source=source))
278
  except Exception as e2:
279
  return DownloadResult(url=url, ok=False,
280
  error=clean_error(f"{source}: {e2}"))
backend/app/services/dubber/subtitle_render.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chèn HARD SUBTITLE (burn cứng) vào video — kiểu CapCut.
2
+
3
+ Đầu vào là danh sách ĐOẠN text (mỗi đoạn có thời gian + style + vị trí riêng),
4
+ đầu ra là file ASS rồi ffmpeg burn vào video.
5
+
6
+ - Mỗi đoạn tự có: font, cỡ chữ, màu chữ, màu highlight, kiểu nền, vị trí (x,y %),
7
+ bề rộng vùng (w %). Mới tạo thì các đoạn giống nhau, user chỉnh riêng sau.
8
+ - 3 kiểu hiển thị (mode, chung cả video):
9
+ "whole" : hiện cả đoạn suốt thời lượng.
10
+ "progressive" : chữ hiện dần từng từ theo lời đọc.
11
+ "highlight" : hiện cả đoạn, tô sáng từng từ theo lời đọc (\\kf).
12
+ - Câu quá dài được tách đoạn tự động (split_lines) để không quá nhiều chữ 1 khung.
13
+
14
+ Font: dùng font ép kèm trong app (thư mục assets/fonts) nếu có, để bản burn
15
+ giống bản xem trước, không phụ thuộc font hệ thống.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import os
22
+ import re
23
+ import shutil
24
+ import subprocess
25
+
26
+ FFMPEG = shutil.which("ffmpeg") or "ffmpeg"
27
+ FFPROBE = shutil.which("ffprobe") or "ffprobe"
28
+
29
+ # thư mục font ép kèm (nếu có) -> libass sẽ nạp qua fontsdir
30
+ FONTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(
31
+ os.path.abspath(__file__)))), "assets", "fonts")
32
+
33
+ ALIGN_C = 5 # \an5: neo tâm (dùng với \pos)
34
+
35
+
36
+ # ------------------------------------------------------------- helpers ---
37
+
38
+ def probe_size(video: str) -> tuple[int, int]:
39
+ try:
40
+ out = subprocess.run(
41
+ [FFPROBE, "-v", "error", "-select_streams", "v:0",
42
+ "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", video],
43
+ capture_output=True, text=True, check=True).stdout.strip()
44
+ w, h = out.split("x")[:2]
45
+ return int(w), int(h)
46
+ except Exception:
47
+ return 1080, 1920
48
+
49
+
50
+ def _t(s: str) -> float:
51
+ h, m, rest = s.strip().split(":")
52
+ sec, ms = re.split("[,.]", rest)
53
+ return int(h) * 3600 + int(m) * 60 + int(sec) + int(ms) / 1000
54
+
55
+
56
+ def parse_srt(path: str) -> list[dict]:
57
+ """SRT -> [{start, end, text}] (giây)."""
58
+ out: list[dict] = []
59
+ with open(path, encoding="utf-8") as f:
60
+ blocks = re.split(r"\n\s*\n", f.read().strip())
61
+ for b in blocks:
62
+ rows = [r for r in b.splitlines() if r.strip()]
63
+ ti = next((i for i, r in enumerate(rows) if "-->" in r), None)
64
+ if ti is None:
65
+ continue
66
+ a, bb = rows[ti].split("-->")
67
+ text = " ".join(rows[ti + 1:]).strip()
68
+ if text and "[No subtitle" not in text:
69
+ out.append({"start": _t(a), "end": _t(bb), "text": text})
70
+ return out
71
+
72
+
73
+ def words_for(text: str, start: float, end: float) -> list[dict]:
74
+ """Chia đều thời gian cho từng từ theo độ dài ký tự."""
75
+ words = (text or "").split()
76
+ dur = max(0.2, end - start)
77
+ weights = [len(w) + 1 for w in words]
78
+ tot = sum(weights) or 1
79
+ t = start
80
+ out = []
81
+ for w, wt in zip(words, weights):
82
+ wd = dur * wt / tot
83
+ out.append({"w": w, "start": t, "end": t + wd})
84
+ t += wd
85
+ return out
86
+
87
+
88
+ def split_lines(lines: list[dict], max_words: int = 7,
89
+ max_dur: float = 3.6) -> list[dict]:
90
+ """Tách câu dài thành ĐOẠN nhỏ (<= max_words từ & <= max_dur giây) + mốc từng từ.
91
+ Trả về danh sách đoạn: {start, end, text, words:[{w,start,end}]}."""
92
+ segs: list[dict] = []
93
+ for ln in lines:
94
+ words = ln["text"].split()
95
+ if not words:
96
+ continue
97
+ wt = words_for(ln["text"], ln["start"], ln["end"])
98
+ n = max(1, math.ceil(len(words) / max_words),
99
+ math.ceil((ln["end"] - ln["start"]) / max_dur))
100
+ per = math.ceil(len(words) / n)
101
+ for ci in range(0, len(words), per):
102
+ chunk = wt[ci:ci + per]
103
+ if not chunk:
104
+ continue
105
+ segs.append({
106
+ "start": chunk[0]["start"], "end": chunk[-1]["end"],
107
+ "text": " ".join(x["w"] for x in chunk), "words": chunk,
108
+ })
109
+ return segs
110
+
111
+
112
+ # ---------------------------------------------------------------- ASS ---
113
+
114
+ def _ass_color(hex_str: str, alpha: str = "00") -> str:
115
+ h = (hex_str or "#FFFFFF").lstrip("#")
116
+ if len(h) != 6:
117
+ h = "FFFFFF"
118
+ r, g, b = h[0:2], h[2:4], h[4:6]
119
+ return f"&H{alpha}{b}{g}{r}".upper()
120
+
121
+
122
+ def _ass_ts(t: float) -> str:
123
+ t = max(0.0, t)
124
+ h = int(t // 3600); t -= h * 3600
125
+ m = int(t // 60); t -= m * 60
126
+ s = int(t); cs = int(round((t - s) * 100))
127
+ if cs >= 100:
128
+ s += 1; cs = 0
129
+ return f"{h:d}:{m:02d}:{s:02d}.{cs:02d}"
130
+
131
+
132
+ def _esc(txt: str) -> str:
133
+ return txt.replace("\\", "").replace("{", "(").replace("}", ")").replace("\n", " ")
134
+
135
+
136
+ def _wrap(text: str, w_frac: float, fsize: int, play_w: int) -> str:
137
+ """Chèn \\N để chữ không tràn quá bề rộng vùng.
138
+
139
+ Ước lượng bề rộng trung bình 1 ký tự ~ 0.5*cỡ chữ (khớp Arial/sans thực tế,
140
+ trùng cách trình duyệt xuống dòng ở bản xem trước). Trước dùng 0.6 -> cắt dòng
141
+ sớm -> chữ dồn xuống trông như dọc trên video hẹp.
142
+ """
143
+ box_px = max(80, w_frac * play_w)
144
+ cpl = max(8, int(box_px / (fsize * 0.5))) # số ký tự / dòng (xấp xỉ)
145
+ words = text.split()
146
+ lines, cur = [], ""
147
+ for w in words:
148
+ if cur and len(cur) + 1 + len(w) > cpl:
149
+ lines.append(cur); cur = w
150
+ else:
151
+ cur = (cur + " " + w).strip()
152
+ if cur:
153
+ lines.append(cur)
154
+ return "\\N".join(lines)
155
+
156
+
157
+ def _style_line(name: str, st: dict, mode: str) -> str:
158
+ font = st.get("font", "Arial")
159
+ fsize = int(st.get("fontSize") or 48)
160
+ color = _ass_color(st.get("color", "#FFFFFF"))
161
+ hi = _ass_color(st.get("highlight", "#FFD400"))
162
+ bg = st.get("bg", "outlineThin")
163
+ if bg in ("boxDark", "boxSolid", "boxRound", "bar", "boxColor"):
164
+ border_style, outline, shadow = 3, 8, 0
165
+ outline_col = _ass_color(st.get("highlight", "#000000")) if bg == "boxColor" else "&H80000000"
166
+ back_col = outline_col
167
+ elif bg == "none":
168
+ border_style, outline, shadow = 1, 0, 0
169
+ outline_col = "&H00000000"; back_col = "&H00000000"
170
+ elif bg == "shadow":
171
+ border_style, outline, shadow = 1, 0, 3
172
+ outline_col = "&H00000000"; back_col = "&H90000000"
173
+ elif bg == "outlineWhite":
174
+ border_style, outline, shadow = 1, 3, 0
175
+ outline_col = "&H00FFFFFF"; back_col = "&H00000000"
176
+ elif bg == "outlineThick":
177
+ border_style, outline, shadow = 1, 5, 0
178
+ outline_col = "&H00000000"; back_col = "&H00000000"
179
+ else: # outlineThin / glow default
180
+ border_style, outline, shadow = 1, 3, 1
181
+ outline_col = "&H00000000"; back_col = "&H80000000"
182
+ # highlight: phần đã đọc = PrimaryColour(hi); chưa đọc = SecondaryColour(color)
183
+ if mode == "highlight":
184
+ primary, secondary = hi, color
185
+ else:
186
+ primary, secondary = color, color
187
+ return (f"Style: {name},{font},{fsize},{primary},{secondary},{outline_col},"
188
+ f"{back_col},1,0,0,0,100,100,0,0,{border_style},{outline},{shadow},"
189
+ f"{ALIGN_C},20,20,20,1")
190
+
191
+
192
+ def build_ass(segments: list[dict], out_path: str, mode: str = "whole",
193
+ res: tuple[int, int] = (1080, 1920)) -> str:
194
+ """segments: mỗi phần tử {start,end,text,words?,style{...}}.
195
+ style: {font,fontSize,color,highlight,bg,x,y,w} (x,y,w theo %)."""
196
+ W, H = res
197
+ head = [
198
+ "[Script Info]", "ScriptType: v4.00+", f"PlayResX: {W}", f"PlayResY: {H}",
199
+ "WrapStyle: 2", "ScaledBorderAndShadow: yes", "",
200
+ "[V4+ Styles]",
201
+ ("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, "
202
+ "OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, "
203
+ "ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, "
204
+ "MarginL, MarginR, MarginV, Encoding"),
205
+ ]
206
+ styles, events = [], []
207
+ for i, seg in enumerate(segments):
208
+ st = seg.get("style", {})
209
+ name = f"S{i}"
210
+ styles.append(_style_line(name, st, mode))
211
+ cx = int((st.get("x", 50) / 100.0) * W)
212
+ cy = int((st.get("y", 86) / 100.0) * H)
213
+ fsize = int(st.get("fontSize") or 48)
214
+ wfrac = float(st.get("w", 82)) / 100.0
215
+ pos = f"{{\\pos({cx},{cy})}}"
216
+ words = seg.get("words") or words_for(seg["text"], seg["start"], seg["end"])
217
+ # breaks = index các từ BẮT ĐẦU dòng mới (do FE đo chữ thật gửi lên). Nếu
218
+ # không có thì tự ước lượng (_wrap) — kém khớp hơn.
219
+ breaks = set(seg.get("breaks") or [])
220
+
221
+ def joinw(rendered):
222
+ out = []
223
+ for k, rs in enumerate(rendered):
224
+ if k > 0:
225
+ out.append("\\N" if k in breaks else " ")
226
+ out.append(rs)
227
+ return "".join(out)
228
+
229
+ has_breaks = bool(seg.get("breaks"))
230
+ if mode == "progressive":
231
+ for j, wd in enumerate(words):
232
+ start = wd["start"]
233
+ end = words[j + 1]["start"] if j + 1 < len(words) else seg["end"]
234
+ if has_breaks:
235
+ txt = joinw([_esc(x["w"]) for x in words[:j + 1]])
236
+ else:
237
+ txt = _wrap(" ".join(x["w"] for x in words[:j + 1]), wfrac, fsize, W)
238
+ events.append(f"Dialogue: 0,{_ass_ts(start)},{_ass_ts(end)},{name},,0,0,0,,{pos}{txt}")
239
+ elif mode == "highlight":
240
+ kfs = [f"{{\\kf{max(1, int(round((wd['end'] - wd['start']) * 100)))}}}{_esc(wd['w'])}" for wd in words]
241
+ txt = joinw(kfs) if has_breaks else " ".join(kfs)
242
+ events.append(f"Dialogue: 0,{_ass_ts(seg['start'])},{_ass_ts(seg['end'])},{name},,0,0,0,,{pos}{txt}")
243
+ else: # whole
244
+ if has_breaks:
245
+ txt = joinw([_esc(x["w"]) for x in words])
246
+ else:
247
+ txt = _wrap(_esc(seg["text"]), wfrac, fsize, W)
248
+ events.append(f"Dialogue: 0,{_ass_ts(seg['start'])},{_ass_ts(seg['end'])},{name},,0,0,0,,{pos}{txt}")
249
+
250
+ body = head + styles + ["", "[Events]",
251
+ ("Format: Layer, Start, End, Style, Name, MarginL, "
252
+ "MarginR, MarginV, Effect, Text")] + events
253
+ with open(out_path, "w", encoding="utf-8") as f:
254
+ f.write("\n".join(body) + "\n")
255
+ return out_path
256
+
257
+
258
+ def burn(video: str, ass_path: str, out_path: str) -> str:
259
+ """Burn cứng ASS vào video (chạy cwd = thư mục ASS để né escape ổ đĩa Windows)."""
260
+ d = os.path.dirname(ass_path)
261
+ base = os.path.basename(ass_path)
262
+ vf = f"subtitles={base}"
263
+ if os.path.isdir(FONTS_DIR):
264
+ vf += f":fontsdir={FONTS_DIR.replace(os.sep, '/')}"
265
+ subprocess.run(
266
+ [FFMPEG, "-y", "-hide_banner", "-loglevel", "error",
267
+ "-i", video, "-vf", vf,
268
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20",
269
+ "-pix_fmt", "yuv420p", "-c:a", "copy", out_path],
270
+ check=True, capture_output=True, cwd=d)
271
+ return out_path
backend/app/services/dubber/translate.py CHANGED
@@ -8,6 +8,7 @@
8
 
9
  from __future__ import annotations
10
 
 
11
  from dataclasses import dataclass
12
 
13
  from ...config import settings
@@ -35,17 +36,18 @@ def char_budget(seg: Segment, target_lang: str) -> int:
35
  def _prompt(seg: Segment, target_lang: str, budget: int) -> str:
36
  name = LANG_NAME.get(target_lang, target_lang)
37
  return (
38
- f"You are a professional advertising voice-over translator for short "
39
- f"product videos (TikTok/Reels style).\n"
40
- f"Translate the line below into natural, SPOKEN {name} with an ENGAGING "
41
- f"ADVERTISING tone: catchy, persuasive, energetic, emphasizing the "
42
- f"product's appeal and benefits — the way a native {name} marketer would "
43
- f"actually pitch it — while staying faithful to the original meaning.\n"
44
- f"It must be speakable in about {seg.dur:.1f} seconds, so keep it within "
45
- f"~{budget} characters. Prefer a punchy, concise paraphrase over a literal "
46
- f"translation so it fits the time AND sounds catchy. Keep proper nouns, "
47
- f"brand names and numbers. Return ONLY the translated line — no quotes, "
48
- f"no notes, no explanation.\n\n"
 
49
  f"Line: {seg.text}"
50
  )
51
 
@@ -83,9 +85,63 @@ def translate_line(seg: Segment, target_lang: str) -> str:
83
  return seg.text # cùng lắm giữ nguyên để không vỡ luồng
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def translate_all(segs: list[Segment], target_lang: str) -> list[TranslatedLine]:
87
  if target_lang not in LANG_NAME:
88
  raise ValueError(f"Ngôn ngữ đích chưa hỗ trợ: {target_lang}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  out = []
90
  for s in segs:
91
  txt = translate_line(s, target_lang)
 
8
 
9
  from __future__ import annotations
10
 
11
+ import re
12
  from dataclasses import dataclass
13
 
14
  from ...config import settings
 
36
  def _prompt(seg: Segment, target_lang: str, budget: int) -> str:
37
  name = LANG_NAME.get(target_lang, target_lang)
38
  return (
39
+ f"Translate the line below into natural, spoken {name} for video dubbing.\n"
40
+ f"Rules:\n"
41
+ f"- Translate FAITHFULLY — keep the EXACT meaning of the original. Do NOT "
42
+ f"add, remove, embellish or invent anything. No marketing or promotional "
43
+ f"wording unless it is actually said in the original.\n"
44
+ f"- Make it sound like natural spoken {name}, the way a real person would "
45
+ f"actually say that same sentence.\n"
46
+ f"- It should be speakable in about {seg.dur:.1f} seconds (roughly "
47
+ f"{budget} characters); if needed phrase it concisely, but NEVER drop or "
48
+ f"change the meaning to fit the time.\n"
49
+ f"- Keep proper nouns, brand names and numbers exactly.\n"
50
+ f"Return ONLY the translated line — no quotes, no notes, no explanation.\n\n"
51
  f"Line: {seg.text}"
52
  )
53
 
 
85
  return seg.text # cùng lắm giữ nguyên để không vỡ luồng
86
 
87
 
88
+ def _batch_prompt(segs: list[Segment], target_lang: str) -> str:
89
+ """Prompt DỊCH GỘP: đưa TẤT CẢ câu vào 1 lần gọi, đánh số để map lại."""
90
+ name = LANG_NAME.get(target_lang, target_lang)
91
+ rows = []
92
+ for i, s in enumerate(segs, 1):
93
+ b = char_budget(s, target_lang)
94
+ rows.append(f"{i}. [~{s.dur:.1f}s, <= {b} chars] {s.text}")
95
+ body = "\n".join(rows)
96
+ return (
97
+ f"You are translating short video subtitles into {name} for dubbing.\n"
98
+ f"Translate EACH numbered line below into natural, spoken {name}.\n"
99
+ f"Rules:\n"
100
+ f"- Translate FAITHFULLY — keep the EXACT meaning of each line. Do NOT add, "
101
+ f"remove, merge, split or invent anything. No marketing wording unless it is "
102
+ f"actually said.\n"
103
+ f"- Natural spoken {name}, the way a real person would say that line.\n"
104
+ f"- Keep each line within its time budget (concise), but never drop meaning.\n"
105
+ f"- Keep proper nouns, brand names and numbers exactly.\n"
106
+ f"Return EXACTLY one translation per input line, in the SAME order, each on "
107
+ f"its own line, prefixed with its number and a period (e.g. '1. ...'). "
108
+ f"Output ONLY these numbered lines, nothing else.\n\n"
109
+ f"Lines:\n{body}"
110
+ )
111
+
112
+
113
+ def _parse_batch(text: str) -> dict[int, str]:
114
+ out: dict[int, str] = {}
115
+ for raw in (text or "").splitlines():
116
+ m = re.match(r"\s*(\d+)[.)]\s*(.+)", raw)
117
+ if m:
118
+ out[int(m.group(1))] = m.group(2).strip()
119
+ return out
120
+
121
+
122
  def translate_all(segs: list[Segment], target_lang: str) -> list[TranslatedLine]:
123
  if target_lang not in LANG_NAME:
124
  raise ValueError(f"Ngôn ngữ đích chưa hỗ trợ: {target_lang}")
125
+ if not segs:
126
+ return []
127
+
128
+ # 1) DỊCH GỘP: 1 lần gọi cho tất cả câu (tránh 429 do gọi từng câu).
129
+ try:
130
+ prompt = _batch_prompt(segs, target_lang)
131
+ try:
132
+ resp = _gemini(prompt)
133
+ except Exception:
134
+ resp = _groq_llm(prompt)
135
+ parsed = _parse_batch(resp)
136
+ if all(i in parsed for i in range(1, len(segs) + 1)):
137
+ return [TranslatedLine(s.start, s.end, s.text,
138
+ parsed.get(i + 1) or s.text,
139
+ char_budget(s, target_lang))
140
+ for i, s in enumerate(segs)]
141
+ except Exception:
142
+ pass
143
+
144
+ # 2) DỰ PHÒNG: dịch từng câu (chỉ khi gộp lỗi/không parse được).
145
  out = []
146
  for s in segs:
147
  txt = translate_line(s, target_lang)
frontend/src/api.js CHANGED
@@ -61,6 +61,9 @@ export const api = {
61
  dubVoices: (lang) => fetch(BASE + `/api/dub/voices?lang=${lang}`).then((r) => r.json()),
62
  dubStart: (req) => jpost("/api/dub/start", req),
63
  dubTts: (req) => jpost("/api/dub/tts", req),
 
 
 
64
 
65
  // Drive
66
  driveStatus: (username) => fetch(BASE + `/api/drive/status?username=${encodeURIComponent(username)}`).then((r) => r.json()),
 
61
  dubVoices: (lang) => fetch(BASE + `/api/dub/voices?lang=${lang}`).then((r) => r.json()),
62
  dubStart: (req) => jpost("/api/dub/start", req),
63
  dubTts: (req) => jpost("/api/dub/tts", req),
64
+ // Hard subtitle
65
+ subtitlePlan: (session, srt) => jpost("/api/dub/subtitle/plan", { session, srt }),
66
+ subtitleBurn: (req) => jpost("/api/dub/subtitle", req),
67
 
68
  // Drive
69
  driveStatus: (username) => fetch(BASE + `/api/drive/status?username=${encodeURIComponent(username)}`).then((r) => r.json()),
frontend/src/components/SubtitleEditor.jsx ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { api, fileUrl, pollJob } from "../api";
3
+ import { IcDownload, IcPlus, IcTrash } from "./Icons";
4
+
5
+ // Font hệ thống (có sẵn trên Windows + hỗ trợ tiếng Việt) -> burn ffmpeg khớp preview.
6
+ const FONTS = [
7
+ { label: "Arial", css: "Arial, sans-serif", ass: "Arial" },
8
+ { label: "Tahoma", css: "Tahoma, sans-serif", ass: "Tahoma" },
9
+ { label: "Verdana", css: "Verdana, sans-serif", ass: "Verdana" },
10
+ { label: "Segoe UI", css: "'Segoe UI', sans-serif", ass: "Segoe UI" },
11
+ { label: "Trebuchet MS", css: "'Trebuchet MS', sans-serif", ass: "Trebuchet MS" },
12
+ { label: "Georgia (serif)", css: "Georgia, serif", ass: "Georgia" },
13
+ { label: "Times New Roman (serif)", css: "'Times New Roman', serif", ass: "Times New Roman" },
14
+ ];
15
+ const BGS = [
16
+ ["Viền đen mỏng", "outlineThin"], ["Viền đen đậm", "outlineThick"],
17
+ ["Viền trắng", "outlineWhite"], ["Bóng đổ", "shadow"], ["Phát sáng", "glow"],
18
+ ["Hộp đen mờ", "boxDark"], ["Hộp đen đậm", "boxSolid"], ["Hộp bo tròn", "boxRound"],
19
+ ["Thanh nền cả dòng", "bar"], ["Hộp màu highlight", "boxColor"], ["Không nền", "none"],
20
+ ];
21
+ const MODES = [
22
+ ["whole", "Hiện cả câu"], ["progressive", "Hiện dần"], ["highlight", "Highlight từng chữ"],
23
+ ];
24
+ const DEF = { font: "Arial", fontSize: 54, color: "#ffffff", highlight: "#ffd400", bg: "outlineThin", x: 50, y: 86, w: 82 };
25
+ const cssOf = (ass) => (FONTS.find((f) => f.ass === ass) || FONTS[0]).css;
26
+ const trunc = (t, n) => { t = (t || "").trim(); return t.length > n ? t.slice(0, n).trim() + "…" : t; };
27
+ const wordsFor = (text, start, end) => {
28
+ const words = (text || "").split(/\s+/).filter(Boolean);
29
+ const dur = Math.max(0.2, end - start);
30
+ const wt = words.map((w) => w.length + 1); const tot = wt.reduce((a, b) => a + b, 0) || 1;
31
+ 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; });
32
+ };
33
+
34
+ export default function SubtitleEditor({ session, videoUrl, videoRel, srtRel, username, onClose }) {
35
+ const [segs, setSegs] = useState([]); // {start,end,text,words,locked,style}
36
+ const [sel, setSel] = useState(0);
37
+ const [mode, setMode] = useState("whole");
38
+ const [playing, setPlaying] = useState(false);
39
+ const [t, setT] = useState(0);
40
+ const [dur, setDur] = useState(0);
41
+ const [thumbs, setThumbs] = useState([]);
42
+ const [busy, setBusy] = useState(false);
43
+ const [result, setResult] = useState(null);
44
+ const [editing, setEditing] = useState(false);
45
+ const [, force] = useState(0);
46
+ const videoRef = useRef();
47
+ const wrapRef = useRef();
48
+ const nat = useRef({ w: 1080, h: 1920 });
49
+ const act = useRef(null);
50
+
51
+ // Tự sinh phụ đề từ lời dịch (SRT). User bấm nút này khi muốn.
52
+ const autoSubtitle = async () => {
53
+ try {
54
+ const r = await api.subtitlePlan(session, srtRel);
55
+ const loaded = (r.segments || []).map((s) => ({
56
+ ...s, locked: true, words: s.words || wordsFor(s.text, s.start, s.end),
57
+ style: JSON.parse(JSON.stringify(DEF)),
58
+ }));
59
+ setSegs((cur) => [...cur.filter((x) => !x.locked), ...loaded]);
60
+ } catch (e) { alert("Lỗi tạo phụ đề: " + e.message); }
61
+ };
62
+
63
+ // chụp ~8 thumbnail từ video (video same-origin nên canvas không bị taint)
64
+ useEffect(() => {
65
+ const v = document.createElement("video");
66
+ v.src = videoUrl; v.muted = true; v.crossOrigin = "anonymous";
67
+ const seek = (time) => new Promise((res) => { const h = () => { v.removeEventListener("seeked", h); res(); }; v.addEventListener("seeked", h); v.currentTime = time; });
68
+ v.addEventListener("loadedmetadata", async () => {
69
+ try {
70
+ const N = 8, cv = document.createElement("canvas"); cv.width = 64; cv.height = 114;
71
+ const ctx = cv.getContext("2d"); const out = [];
72
+ for (let i = 0; i < N; i++) { await seek(v.duration * (i + 0.5) / N); ctx.drawImage(v, 0, 0, cv.width, cv.height); out.push(cv.toDataURL("image/jpeg", 0.5)); }
73
+ setThumbs(out);
74
+ } catch { /* bỏ qua nếu chụp lỗi */ }
75
+ });
76
+ // eslint-disable-next-line
77
+ }, [videoUrl]);
78
+
79
+ // đồng bộ thời gian video -> state (rAF cho mượt)
80
+ useEffect(() => {
81
+ const v = videoRef.current; if (!v) return; let raf;
82
+ const loop = () => { setT(v.currentTime); raf = requestAnimationFrame(loop); };
83
+ const onMeta = () => { setDur(v.duration); nat.current = { w: v.videoWidth || 1080, h: v.videoHeight || 1920 }; };
84
+ const onPlay = () => { setPlaying(true); cancelAnimationFrame(raf); loop(); };
85
+ const onPause = () => { setPlaying(false); cancelAnimationFrame(raf); setT(v.currentTime); };
86
+ v.addEventListener("loadedmetadata", onMeta); v.addEventListener("play", onPlay); v.addEventListener("pause", onPause); v.addEventListener("seeked", () => setT(v.currentTime));
87
+ return () => { cancelAnimationFrame(raf); v.removeEventListener("loadedmetadata", onMeta); v.removeEventListener("play", onPlay); v.removeEventListener("pause", onPause); };
88
+ // eslint-disable-next-line
89
+ }, []);
90
+
91
+ const patch = (i, p) => setSegs((cur) => cur.map((s, j) => (j === i ? { ...s, ...p } : s)));
92
+ const patchStyle = (p) => setSegs((cur) => cur.map((s, j) => (j === sel ? { ...s, style: { ...s.style, ...p } } : s)));
93
+ const cur = () => segs[sel];
94
+
95
+ // đoạn đang hiển thị theo thời gian (nhiều đoạn có thể cùng lúc)
96
+ const activeIdx = segs.map((s, i) => i).filter((i) => t >= segs[i].start && t <= segs[i].end);
97
+ useEffect(() => { if (!editing && activeIdx.length && !activeIdx.includes(sel)) setSel(activeIdx[activeIdx.length - 1]); });
98
+
99
+ const total = dur || 1;
100
+ const scale = () => { const v = videoRef.current; return v && v.videoHeight ? v.clientHeight / v.videoHeight : 1; };
101
+
102
+ // ---- lanes cho timeline ----
103
+ const lanes = (() => {
104
+ const order = segs.map((s, i) => i).sort((a, b) => segs[a].start - segs[b].start);
105
+ const ends = []; const lane = {};
106
+ order.forEach((i) => { const s = segs[i]; let L = ends.findIndex((e) => s.start >= e - 0.001); if (L < 0) { L = ends.length; ends.push(s.end); } else ends[L] = s.end; lane[i] = L; });
107
+ return { lane, n: Math.max(1, ends.length) };
108
+ })();
109
+
110
+ const seekTo = (time) => { const v = videoRef.current; if (v) { v.currentTime = Math.max(0, Math.min(total, time)); } setPlaying(false); if (v) v.pause(); };
111
+
112
+ // ---- kéo/giãn ô text trên video ----
113
+ const boxDown = (i) => (e) => {
114
+ if (editing || e.target.dataset.h) return;
115
+ setSel(i); const v = videoRef.current; if (v) v.pause();
116
+ act.current = { kind: "move", i, sx: e.clientX, sy: e.clientY, moved: false };
117
+ e.currentTarget.setPointerCapture(e.pointerId);
118
+ };
119
+ const handleDown = (i) => (e) => {
120
+ if (editing) return; e.stopPropagation(); setSel(i); const v = videoRef.current; if (v) v.pause();
121
+ act.current = { kind: "resize", i, sx: e.clientX, moved: false };
122
+ e.currentTarget.parentElement.setPointerCapture(e.pointerId);
123
+ };
124
+ const boxMove = (e) => {
125
+ const a = act.current; if (!a) return;
126
+ if (!a.moved && Math.hypot(e.clientX - a.sx, (e.clientY || 0) - (a.sy || 0)) < 3) return;
127
+ a.moved = true; const r = wrapRef.current.getBoundingClientRect(); const s = segs[a.i].style;
128
+ if (a.kind === "move") { const hw = s.w / 2; patch(a.i, { style: { ...s, x: Math.max(hw + 1, Math.min(99 - hw, (e.clientX - r.left) / r.width * 100)), y: Math.max(6, Math.min(94, (e.clientY - r.top) / r.height * 100)) } }); }
129
+ else { const dx = Math.abs((e.clientX - r.left) / r.width * 100 - s.x); patch(a.i, { style: { ...s, w: Math.max(24, Math.min(96, dx * 2)) } }); }
130
+ };
131
+ const boxUp = (i) => (e) => {
132
+ const a = act.current; if (a && !a.moved && !segs[i].locked) startEdit(i);
133
+ act.current = null;
134
+ };
135
+
136
+ const startEdit = (i) => { setSel(i); setEditing(true); const v = videoRef.current; if (v) v.pause(); setTimeout(() => { const el = document.getElementById("subedit-" + i); if (el) { el.focus(); const rg = document.createRange(); rg.selectNodeContents(el); const se = window.getSelection(); se.removeAllRanges(); se.addRange(rg); } }, 0); };
137
+ const endEdit = (i) => (e) => { setEditing(false); const txt = (e.currentTarget.textContent || "").trim() || "Text"; setSegs((cur) => cur.map((s, j) => (j === i ? { ...s, text: txt, words: wordsFor(txt, s.start, s.end) } : s))); };
138
+
139
+ const addText = () => {
140
+ const start = Math.max(0, Math.min(t, total - 1)); const end = Math.min(total, start + 2.5);
141
+ const style = JSON.parse(JSON.stringify(DEF)); style.y = 50;
142
+ const seg = { start, end, text: "Text mới", locked: false, style, words: wordsFor("Text mới", start, end) };
143
+ setSegs((cur) => { const n = [...cur, seg]; setSel(n.length - 1); return n; });
144
+ seekTo((start + end) / 2); setTimeout(() => startEdit(segs.length), 30);
145
+ };
146
+ const delText = () => { const s = cur(); if (!s || s.locked) return; setSegs((c) => c.filter((_, j) => j !== sel)); setSel(0); };
147
+ const applyAll = () => { const s = cur().style; setSegs((c) => c.map((sg) => ({ ...sg, style: { ...JSON.parse(JSON.stringify(s)), x: sg.style.x, y: sg.style.y } }))); };
148
+
149
+ // Đo chữ thật (canvas, đúng font/cỡ ở độ phân giải GỐC của video) -> trả về
150
+ // index các từ BẮT ĐẦU dòng mới, để bản burn xuống dòng GIỐNG HỆT preview.
151
+ const measureBreaks = (seg) => {
152
+ const v = videoRef.current; const natW = (v && v.videoWidth) || 1080;
153
+ const st = seg.style; const boxPx = Math.max(80, (st.w / 100) * natW * 0.97);
154
+ const words = (seg.text || "").split(/\s+/).filter(Boolean);
155
+ const cv = measureBreaks._cv || (measureBreaks._cv = document.createElement("canvas"));
156
+ const ctx = cv.getContext("2d");
157
+ ctx.font = `bold ${st.fontSize}px ${cssOf(st.font)}`; // ASS render Bold=1 -> đo bold cho khớp
158
+ const sp = ctx.measureText(" ").width;
159
+ const breaks = []; let lineW = 0;
160
+ words.forEach((w, i) => {
161
+ const ww = ctx.measureText(w).width;
162
+ if (i > 0 && lineW + sp + ww > boxPx) { breaks.push(i); lineW = ww; }
163
+ else { lineW = i === 0 ? ww : lineW + sp + ww; }
164
+ });
165
+ return breaks;
166
+ };
167
+
168
+ const burn = async () => {
169
+ if (!segs.length) return alert("Chưa có đoạn text nào. Bấm 'Tự tạo phụ đề' hoặc 'Thêm text'.");
170
+ setBusy(true); setResult(null);
171
+ try {
172
+ const { job_id } = await api.subtitleBurn({
173
+ session, video: videoRel, mode, username: username || "",
174
+ segments: segs.map((s) => ({ start: s.start, end: s.end, text: s.text, style: s.style, breaks: measureBreaks(s) })),
175
+ });
176
+ const done = await pollJob(job_id, () => {});
177
+ const out = done.result?.output || (done.items || []).find((i) => i.status === "done")?.result;
178
+ if (out) setResult(out); else alert("Lỗi tạo video phụ đề (xem log).");
179
+ } catch (e) { alert("Lỗi: " + e.message); } finally { setBusy(false); }
180
+ };
181
+
182
+ // ---- render 1 ô text ----
183
+ const boxStyle = (s, on) => {
184
+ const st = s.style; const px = st.fontSize * scale();
185
+ const base = { position: "absolute", left: st.x + "%", top: st.y + "%", transform: "translate(-50%,-50%)", width: st.w + "%", textAlign: "center", lineHeight: 1.25, fontWeight: 700, fontFamily: cssOf(st.font), fontSize: px + "px", color: st.color, boxSizing: "border-box", cursor: editing ? "text" : "move", outline: on ? "1.5px dashed rgba(255,255,255,.85)" : "none", zIndex: on ? 5 : 2, wordWrap: "break-word" };
186
+ const b = st.bg; const ol = (p, c) => `${-p}px ${-p}px 0 ${c},${p}px ${-p}px 0 ${c},${-p}px ${p}px 0 ${c},${p}px ${p}px 0 ${c},0 ${p * 1.3}px 3px ${c}`;
187
+ if (b === "outlineThin") base.textShadow = ol(1.3 * scale() + 0.5, "#000");
188
+ else if (b === "outlineThick") base.textShadow = ol(2.4 * scale() + 0.5, "#000");
189
+ else if (b === "outlineWhite") base.textShadow = ol(1.6 * scale() + 0.5, "#fff");
190
+ else if (b === "shadow") base.textShadow = "0 3px 7px rgba(0,0,0,.95)";
191
+ else if (b === "glow") base.textShadow = `0 0 9px ${st.highlight},0 0 4px ${st.highlight}`;
192
+ else if (b === "boxDark") { base.background = "rgba(0,0,0,.5)"; base.padding = "4px 10px"; base.borderRadius = "6px"; }
193
+ else if (b === "boxSolid") { base.background = "#000"; base.padding = "4px 10px"; base.borderRadius = "4px"; }
194
+ else if (b === "boxRound") { base.background = "rgba(0,0,0,.62)"; base.padding = "7px 14px"; base.borderRadius = "22px"; }
195
+ else if (b === "bar") { base.background = "rgba(0,0,0,.5)"; base.padding = "7px 8px"; }
196
+ else if (b === "boxColor") { base.background = st.highlight; base.padding = "4px 12px"; base.borderRadius = "6px"; }
197
+ return base;
198
+ };
199
+ const boxContent = (s) => {
200
+ if (editing && segs[sel] === s) return null;
201
+ if (mode === "whole") return s.text;
202
+ if (mode === "progressive") return s.words.filter((w) => t >= w.start).map((w) => w.w).join(" ") || " ";
203
+ return s.words.map((w, i) => <span key={i} style={{ color: t >= w.start ? s.style.highlight : s.style.color }}>{w.w}{i < s.words.length - 1 ? " " : ""}</span>);
204
+ };
205
+
206
+ const fmt = (x) => { x = Math.max(0, x || 0); const m = Math.floor(x / 60), ss = Math.floor(x % 60); return `${String(m).padStart(2, "0")}:${String(ss).padStart(2, "0")}`; };
207
+
208
+ return (
209
+ <div className="card" style={{ borderColor: "var(--orange)" }}>
210
+ <div className="flex between center">
211
+ <div className="panel-title" style={{ margin: 0 }}>Chèn phụ đề (hard sub)</div>
212
+ <button className="btn sm ghost" onClick={onClose}>Đóng</button>
213
+ </div>
214
+
215
+ <div className="grid-2" style={{ gridTemplateColumns: "300px 1fr", gap: 16, marginTop: 10 }}>
216
+ {/* preview + timeline */}
217
+ <div>
218
+ <div ref={wrapRef} style={{ position: "relative", width: "100%", background: "#000", borderRadius: 12, overflow: "hidden" }}>
219
+ <video ref={videoRef} src={videoUrl} onClick={() => { const v = videoRef.current; v.paused ? v.play() : v.pause(); }}
220
+ style={{ display: "block", width: "100%", maxHeight: 460, objectFit: "contain" }} />
221
+ {segs.map((s, i) => (t >= s.start && t <= s.end) ? (
222
+ <div key={i} style={boxStyle(s, i === sel)} onPointerDown={boxDown(i)} onPointerMove={boxMove} onPointerUp={boxUp(i)}>
223
+ <div id={"subedit-" + i} contentEditable={editing && i === sel} suppressContentEditableWarning
224
+ onBlur={endEdit(i)} style={{ outline: "none" }}>
225
+ {boxContent(s)}
226
+ </div>
227
+ {i === sel && !editing && <span data-h="1" onPointerDown={handleDown(i)} style={{ position: "absolute", right: -6, bottom: -6, width: 12, height: 12, background: "var(--orange)", border: "1.5px solid #fff", borderRadius: 3, cursor: "nwse-resize" }} />}
228
+ </div>
229
+ ) : null)}
230
+ </div>
231
+
232
+ <div className="flex center gap8 mt8">
233
+ <button className="btn sm" onClick={() => { const v = videoRef.current; v.paused ? v.play() : v.pause(); }}>{playing ? "❚❚" : "►"}</button>
234
+ <span className="small muted">{fmt(t)} / {fmt(total)}</span>
235
+ <button className="btn sm" style={{ marginLeft: "auto" }} onClick={addText}><IcPlus size={13} /> Thêm text</button>
236
+ </div>
237
+
238
+ {/* timeline */}
239
+ <div style={{ position: "relative", marginTop: 10 }} >
240
+ <div style={{ display: "flex", height: 30, borderRadius: 6, overflow: "hidden", border: "0.5px solid var(--line)", cursor: "pointer" }}
241
+ onPointerDown={(e) => { const r = e.currentTarget.getBoundingClientRect(); seekTo((e.clientX - r.left) / r.width * total); }}>
242
+ {(thumbs.length ? thumbs : Array.from({ length: 8 })).map((th, i) => (
243
+ <div key={i} style={{ flex: 1, background: th ? `center/cover url(${th})` : "#334", borderRight: i < 7 ? "1px solid rgba(255,255,255,.15)" : "none" }} />
244
+ ))}
245
+ </div>
246
+ <div style={{ position: "relative", height: lanes.n * 22 + (lanes.n - 1) * 3, marginTop: 4 }}>
247
+ {segs.map((s, i) => (
248
+ <div key={i} onClick={() => { seekTo((s.start + s.end) / 2); setSel(i); }}
249
+ title={s.text}
250
+ style={{ position: "absolute", left: (s.start / total * 100) + "%", width: Math.max(6, (s.end - s.start) / total * 100) + "%", top: lanes.lane[i] * 25, height: 22, borderRadius: 5, fontSize: 10, lineHeight: "20px", padding: "0 6px", boxSizing: "border-box", overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", cursor: "pointer", border: i === sel ? "1.5px solid var(--orange)" : "1px solid var(--line)", borderStyle: s.locked ? "solid" : "dashed", background: i === sel ? "var(--orange-soft)" : "var(--white)", color: i === sel ? "var(--orange-700)" : "var(--muted)" }}>
251
+ {s.locked ? "🔒 " : ""}{trunc(s.text, 16)}
252
+ </div>
253
+ ))}
254
+ </div>
255
+ <div style={{ position: "absolute", top: 0, width: 2, height: 34 + lanes.n * 22 + (lanes.n - 1) * 3, background: "#ff3b30", left: `calc(${t / total * 100}% - 1px)`, pointerEvents: "none" }} />
256
+ </div>
257
+ </div>
258
+
259
+ {/* controls */}
260
+ <div className="stack" style={{ gap: 12 }}>
261
+ {segs.filter((s) => s.locked).length === 0 && (
262
+ <button className="btn primary" onClick={autoSubtitle}>Tự tạo phụ đề từ lời dịch</button>
263
+ )}
264
+ <div className="flex gap8 center">
265
+ <button className="btn sm ghost" onClick={delText} style={{ display: cur() && !cur().locked ? "inline-flex" : "none" }}><IcTrash size={13} /> Xóa đoạn</button>
266
+ <span className="small muted">{cur() && cur().locked ? "🔒 text lồng tiếng — không xóa được" : ""}</span>
267
+ </div>
268
+
269
+ <div>
270
+ <span className="field-label">Kiểu hiển thị (chung cả video)</span>
271
+ <div className="seg-group">{MODES.map(([id, lb]) => <button key={id} className={mode === id ? "active" : ""} onClick={() => setMode(id)}>{lb}</button>)}</div>
272
+ </div>
273
+
274
+ {cur() && (
275
+ <>
276
+ <div className="row wrap" style={{ gap: 10 }}>
277
+ <div style={{ flex: 1 }}><span className="field-label">Phông</span>
278
+ <select value={cur().style.font} onChange={(e) => patchStyle({ font: e.target.value })} style={{ width: "100%" }}>
279
+ {FONTS.map((f) => <option key={f.ass} value={f.ass}>{f.label}</option>)}</select></div>
280
+ <div style={{ flex: 1 }}><span className="field-label">Kiểu nền</span>
281
+ <select value={cur().style.bg} onChange={(e) => patchStyle({ bg: e.target.value })} style={{ width: "100%" }}>
282
+ {BGS.map(([lb, id]) => <option key={id} value={id}>{lb}</option>)}</select></div>
283
+ </div>
284
+ <div className="row wrap" style={{ gap: 10 }}>
285
+ <label className="field-label" style={{ flex: 1 }}>Màu chữ
286
+ <input type="color" value={cur().style.color} onChange={(e) => patchStyle({ color: e.target.value })}
287
+ style={{ width: "100%", height: 34, marginTop: 4, border: "1px solid var(--line)", borderRadius: 6, padding: 2, cursor: "pointer", background: "var(--white)" }} /></label>
288
+ <label className="field-label" style={{ flex: 1 }}>Màu highlight
289
+ <input type="color" value={cur().style.highlight} onChange={(e) => patchStyle({ highlight: e.target.value })}
290
+ style={{ width: "100%", height: 34, marginTop: 4, border: "1px solid var(--line)", borderRadius: 6, padding: 2, cursor: "pointer", background: "var(--white)" }} /></label>
291
+ </div>
292
+ <div><span className="field-label">Cỡ chữ: {cur().style.fontSize}</span>
293
+ <input className="slider" type="range" min="24" max="120" value={cur().style.fontSize} onChange={(e) => patchStyle({ fontSize: +e.target.value })} /></div>
294
+ <div className="flex gap8">
295
+ <button className="btn sm" onClick={() => patchStyle({ x: 50, y: 86 })}>Về giữa‑đáy</button>
296
+ <button className="btn sm" onClick={applyAll}>Áp style cho mọi đoạn</button>
297
+ </div>
298
+ </>
299
+ )}
300
+
301
+ <button className="btn primary block mt8" onClick={burn} disabled={busy || !segs.length}>
302
+ {busy ? "Đang tạo video có phụ đề…" : "Tạo video có phụ đề"}
303
+ </button>
304
+ <p className="small muted">Đoạn 🔒 là phụ đề từ lời dịch (không xóa). Bấm vào chữ trên video để sửa; kéo để đặt vị trí; kéo góc để giãn vùng.</p>
305
+ </div>
306
+ </div>
307
+
308
+ {result && (
309
+ <div className="mt16" style={{ borderTop: "1px solid var(--line)", paddingTop: 14 }}>
310
+ <div className="panel-title" style={{ marginBottom: 10 }}>Video đã chèn phụ đề</div>
311
+ <div className="flex" style={{ gap: 14, flexWrap: "wrap", alignItems: "flex-start" }}>
312
+ <video src={fileUrl(result.video_url)} controls style={{ maxWidth: 260, maxHeight: 420, borderRadius: 12, background: "#000" }} />
313
+ <a className="btn primary" href={fileUrl(result.video_url)} download><IcDownload size={15} /> Tải video có phụ đề</a>
314
+ </div>
315
+ </div>
316
+ )}
317
+ </div>
318
+ );
319
+ }
frontend/src/pages/CutVideo.jsx CHANGED
@@ -17,10 +17,10 @@ const STEPS = [
17
  ];
18
 
19
  const MODES = [
20
- { id: "even", Icon: IcClips, t: "Cắt đều", d: "Chia N khúc bằng nhau." },
21
- { id: "scene", Icon: IcClock, t: "Chuyển cảnh", d: "Cắt tại điểm chuyển cảnh." },
22
- { id: "highlight", Icon: IcStar, t: "Highlight", d: "Đoạn chuyển động mạnh." },
23
  { id: "smart", Icon: IcAds, t: "Smart (CLIP)", d: "Dùng model CLIP." },
 
 
 
24
  ];
25
 
26
  const fmt = (s) => {
@@ -163,7 +163,7 @@ export default function CutVideo() {
163
  const nav = useNavigate();
164
  const { user } = useAuth();
165
  const [st, set] = useToolState("cut", {
166
- videos: [], active: 0, mode: "even",
167
  countMode: "manual", count: 6, // MẶC ĐỊNH: user tự nhập
168
  results: [], resultSession: null,
169
  busy: false, job: null, // trạng thái xử lý — giữ trong store để
 
17
  ];
18
 
19
  const MODES = [
 
 
 
20
  { id: "smart", Icon: IcAds, t: "Smart (CLIP)", d: "Dùng model CLIP." },
21
+ { id: "highlight", Icon: IcStar, t: "Highlight", d: "Đoạn chuyển động mạnh." },
22
+ { id: "scene", Icon: IcClock, t: "Chuyển cảnh", d: "Cắt tại điểm chuyển cảnh." },
23
+ { id: "even", Icon: IcClips, t: "Cắt đều", d: "Chia N khúc bằng nhau." },
24
  ];
25
 
26
  const fmt = (s) => {
 
163
  const nav = useNavigate();
164
  const { user } = useAuth();
165
  const [st, set] = useToolState("cut", {
166
+ videos: [], active: 0, mode: "smart",
167
  countMode: "manual", count: 6, // MẶC ĐỊNH: user tự nhập
168
  results: [], resultSession: null,
169
  busy: false, job: null, // trạng thái xử lý — giữ trong store để
frontend/src/pages/DownList.jsx CHANGED
@@ -40,6 +40,7 @@ export default function DownList() {
40
  const [showNote, setShowNote] = useState(true);
41
  const [analyzing, setAnalyzing] = useState(false);
42
  const parseTimer = useRef(null);
 
43
 
44
  // Phân tích danh sách link. Gọi tự động (debounce) mỗi khi textarea đổi.
45
  const runParse = async (text) => {
@@ -86,6 +87,8 @@ export default function DownList() {
86
  const sel = st.pick[path] || {};
87
  const tools = TOOLS.filter((t) => sel[t.id]);
88
  if (!tools.length) return alert("Hãy chọn ít nhất một tool để chuyển tiếp.");
 
 
89
  try {
90
  let firstRoute = null;
91
  for (const t of tools) {
@@ -95,6 +98,7 @@ export default function DownList() {
95
  }
96
  if (firstRoute) nav(firstRoute);
97
  } catch (e) { alert("Lỗi: " + e.message); }
 
98
  };
99
 
100
  const downloadAll = () => {
 
40
  const [showNote, setShowNote] = useState(true);
41
  const [analyzing, setAnalyzing] = useState(false);
42
  const parseTimer = useRef(null);
43
+ const forwardingRef = useRef(false);
44
 
45
  // Phân tích danh sách link. Gọi tự động (debounce) mỗi khi textarea đổi.
46
  const runParse = async (text) => {
 
87
  const sel = st.pick[path] || {};
88
  const tools = TOOLS.filter((t) => sel[t.id]);
89
  if (!tools.length) return alert("Hãy chọn ít nhất một tool để chuyển tiếp.");
90
+ if (forwardingRef.current) return; // chống bấm trùng -> đẩy nhiều lần
91
+ forwardingRef.current = true;
92
  try {
93
  let firstRoute = null;
94
  for (const t of tools) {
 
98
  }
99
  if (firstRoute) nav(firstRoute);
100
  } catch (e) { alert("Lỗi: " + e.message); }
101
+ finally { forwardingRef.current = false; }
102
  };
103
 
104
  const downloadAll = () => {
frontend/src/pages/DubVideo.jsx CHANGED
@@ -5,6 +5,7 @@ import { useToolState } from "../store";
5
  import { useAuth } from "../stores/authStore";
6
  import { ProcessRail, FileDrop, Toggle, ProcessingOverlay, CacheNote } from "../components/ui";
7
  import { IcMic, IcDownload, IcPlay, IcDoc, IcText } from "../components/Icons";
 
8
 
9
  const STEPS = [
10
  { t: "Tải video", d: "Tải video nguồn cần dịch." },
@@ -21,9 +22,8 @@ const LANGS = [
21
  // Model chốt theo ngôn ngữ (không cho chọn): vi→VieNeu (clone được), en & fil→Edge TTS.
22
  const MODEL_LABEL = { vi: "VieNeu-TTS", en: "Edge TTS", fil: "Edge TTS" };
23
  const BG = [
24
- { id: "duck", label: "Giảm tiếng gốc" },
25
  { id: "demucs", label: "Tách nhạc (giữ nền)" },
26
- { id: "none", label: "Bỏ tiếng gốc" },
27
  ];
28
  const STYLES = [
29
  { id: "natural", label: "Tự nhiên" },
@@ -60,7 +60,7 @@ export default function DubVideo() {
60
  voiceSource: "preset", // preset | video | upload
61
  voice: "", // id giọng preset
62
  speakerFile: "", speakerName: "",
63
- bg: "duck", style: "natural", multiSpeaker: false,
64
  useQuality: false, temperature: 0.8, topK: 25, repPen: 1.2,
65
  outputs: [],
66
  // khu gen voice từ text
@@ -73,6 +73,7 @@ export default function DubVideo() {
73
  });
74
  const [showNote, setShowNote] = useState(true);
75
  const [uploading, setUploading] = useState(null); // {name,i,n} — video đang tải lên
 
76
  const [voices, setVoices] = useState([]); // giọng cho khu dịch video
77
  const [ttsVoices, setTtsVoices] = useState([]); // giọng cho khu gen voice
78
  const job = st.job;
@@ -359,6 +360,10 @@ export default function DubVideo() {
359
  <a className="btn sm" href={fileUrl(o.video_url)} download><IcDownload size={14} /> Video MP4</a>
360
  <a className="btn sm" href={fileUrl(o.audio_url)} download><IcDownload size={14} /> Audio</a>
361
  <a className="btn sm" href={fileUrl(o.srt_url)} download><IcDoc size={14} /> Subtitle SRT</a>
 
 
 
 
362
  </div>
363
  </div>
364
  ))}
@@ -366,6 +371,12 @@ export default function DubVideo() {
366
  </div>
367
  )}
368
 
 
 
 
 
 
 
369
  {/* Gen voice từ text */}
370
  <div className="card">
371
  <div className="panel-title"><IcText size={16} /> Gen voice từ text</div>
 
5
  import { useAuth } from "../stores/authStore";
6
  import { ProcessRail, FileDrop, Toggle, ProcessingOverlay, CacheNote } from "../components/ui";
7
  import { IcMic, IcDownload, IcPlay, IcDoc, IcText } from "../components/Icons";
8
+ import SubtitleEditor from "../components/SubtitleEditor";
9
 
10
  const STEPS = [
11
  { t: "Tải video", d: "Tải video nguồn cần dịch." },
 
22
  // Model chốt theo ngôn ngữ (không cho chọn): vi→VieNeu (clone được), en & fil→Edge TTS.
23
  const MODEL_LABEL = { vi: "VieNeu-TTS", en: "Edge TTS", fil: "Edge TTS" };
24
  const BG = [
25
+ { id: "none", label: "Xóa bỏ tiếng gốc" },
26
  { id: "demucs", label: "Tách nhạc (giữ nền)" },
 
27
  ];
28
  const STYLES = [
29
  { id: "natural", label: "Tự nhiên" },
 
60
  voiceSource: "preset", // preset | video | upload
61
  voice: "", // id giọng preset
62
  speakerFile: "", speakerName: "",
63
+ bg: "none", style: "natural", multiSpeaker: false,
64
  useQuality: false, temperature: 0.8, topK: 25, repPen: 1.2,
65
  outputs: [],
66
  // khu gen voice từ text
 
73
  });
74
  const [showNote, setShowNote] = useState(true);
75
  const [uploading, setUploading] = useState(null); // {name,i,n} — video đang tải lên
76
+ const [subEd, setSubEd] = useState(null); // editor chèn phụ đề (đẩy video đã dịch vào)
77
  const [voices, setVoices] = useState([]); // giọng cho khu dịch video
78
  const [ttsVoices, setTtsVoices] = useState([]); // giọng cho khu gen voice
79
  const job = st.job;
 
360
  <a className="btn sm" href={fileUrl(o.video_url)} download><IcDownload size={14} /> Video MP4</a>
361
  <a className="btn sm" href={fileUrl(o.audio_url)} download><IcDownload size={14} /> Audio</a>
362
  <a className="btn sm" href={fileUrl(o.srt_url)} download><IcDoc size={14} /> Subtitle SRT</a>
363
+ <button className="btn sm primary" onClick={() => {
364
+ const rel = (u) => (u || "").replace(`/api/files/${st.session}/`, "");
365
+ setSubEd({ videoUrl: fileUrl(o.video_url), videoRel: rel(o.video_url), srtRel: rel(o.srt_url) });
366
+ }}><IcText size={14} /> Chèn phụ đề</button>
367
  </div>
368
  </div>
369
  ))}
 
371
  </div>
372
  )}
373
 
374
+ {subEd && (
375
+ <SubtitleEditor session={st.session} videoUrl={subEd.videoUrl}
376
+ videoRel={subEd.videoRel} srtRel={subEd.srtRel}
377
+ username={user} onClose={() => setSubEd(null)} />
378
+ )}
379
+
380
  {/* Gen voice từ text */}
381
  <div className="card">
382
  <div className="panel-title"><IcText size={16} /> Gen voice từ text</div>
frontend/src/pages/ShuffleVideo.jsx CHANGED
@@ -151,13 +151,17 @@ export default function ShuffleVideo() {
151
  segs.filter((s) => s.order_mode !== "drop").every((s) => s.files.length > 0);
152
 
153
  // Xem BẢNG biến thể (chưa render). keep = do bộ lọc hiện tại quyết định.
 
154
  const showPlan = async () => {
155
  if (!ready) return alert("Mỗi khúc (trừ khúc Bỏ) cần ít nhất một clip.");
 
 
156
  try {
157
  const r = await api.shufflePlan(payload());
158
  set({ plan: r.variants || [] });
159
  if (r.capped) alert(`Danh sách lớn — chỉ hiển thị ${r.variants.length} biến thể đầu.`);
160
  } catch (e) { alert("Lỗi: " + e.message); }
 
161
  };
162
  // Đổi bộ lọc (tương đồng / ngẫu nhiên / giới hạn) -> tự cập nhật lại tick trong bảng.
163
  const refreshPlan = async () => {
@@ -302,8 +306,8 @@ export default function ShuffleVideo() {
302
  <p className="small muted" style={{ marginTop: -6 }}>
303
  Sinh danh sách mọi biến thể (chưa render). Bộ lọc nằm ngay dưới bảng — chỉ dòng còn tick mới render.
304
  </p>
305
- <button className="btn primary block mt12" onClick={showPlan} disabled={!ready}>
306
- <IcShuffle size={16} /> Xem bảng biến thể
307
  </button>
308
  </div>
309
 
 
151
  segs.filter((s) => s.order_mode !== "drop").every((s) => s.files.length > 0);
152
 
153
  // Xem BẢNG biến thể (chưa render). keep = do bộ lọc hiện tại quyết định.
154
+ const [planBusy, setPlanBusy] = useState(false);
155
  const showPlan = async () => {
156
  if (!ready) return alert("Mỗi khúc (trừ khúc Bỏ) cần ít nhất một clip.");
157
+ if (planBusy) return; // chống bấm trùng khi đang tải bảng
158
+ setPlanBusy(true);
159
  try {
160
  const r = await api.shufflePlan(payload());
161
  set({ plan: r.variants || [] });
162
  if (r.capped) alert(`Danh sách lớn — chỉ hiển thị ${r.variants.length} biến thể đầu.`);
163
  } catch (e) { alert("Lỗi: " + e.message); }
164
+ finally { setPlanBusy(false); }
165
  };
166
  // Đổi bộ lọc (tương đồng / ngẫu nhiên / giới hạn) -> tự cập nhật lại tick trong bảng.
167
  const refreshPlan = async () => {
 
306
  <p className="small muted" style={{ marginTop: -6 }}>
307
  Sinh danh sách mọi biến thể (chưa render). Bộ lọc nằm ngay dưới bảng — chỉ dòng còn tick mới render.
308
  </p>
309
+ <button className="btn primary block mt12" onClick={showPlan} disabled={!ready || planBusy}>
310
+ <IcShuffle size={16} /> {planBusy ? "Đang tạo bảng…" : "Xem bảng biến thể"}
311
  </button>
312
  </div>
313