Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

Giọng của tôi: nhân bản giọng người dùng (tải file hoặc thu âm), đọc lời như giọng có sẵn

Lumtek51b24c71a530
diff --git a/cli.mjs b/cli.mjs
index e704ecb..9b2a877 100644
--- a/cli.mjs
+++ b/cli.mjs
@@ -10,6 +10,7 @@
// node cli.mjs templates [--json]
// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--draft] [--llm off] [--json]
// node cli.mjs edit-revise <editId> "<lời sửa>" [--file f] · edit-show <editId> · edit-run <editId> · edit-rm <editId>
+// node cli.mjs voices [--json] · voice-add <file> --name "Tên" --consent [--text "lời đoạn mẫu"] · voice-rename <id> "Tên" · voice-rm <id>
import fs from 'node:fs';
import path from 'node:path';
import { createJob, createJobs, parseTemplateIds, MAX_BATCH, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';
@@ -27,7 +28,8 @@ function usage() {
make --template <id>[,<id>…] --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]
--template 009,045,062 : nhiều mẫu (tối đa ${MAX_BATCH}) → 1 job mỗi mẫu, cùng nội dung + tuỳ chọn, chạy lần lượt.
Kiểm hết trước: 1 id sai / chưa có guidance thì không tạo job nào.
- --music <style|auto|none> --voice <tên giọng|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)
+ --music <style|auto|none> --voice <tên giọng|vc-…|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)
+ vc-xxxxxxxx = giọng nhân bản của bạn (xem: node cli.mjs voices), chỉ đọc tiếng Việt
--duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.
manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viết
jobs/<id>/brief.json + scene/index.html rồi gọi: node cli.mjs render <id>
@@ -56,7 +58,13 @@ function usage() {
edit-revise <editId> "<lời>" | --file <f> sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại
edit-show <editId> [--json] trạng thái, tiến độ, chữ LLM đã sửa, log
edit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)
- edit-rm <editId> xoá hẳn 1 edit (thư mục edits/<id>)`);
+ edit-rm <editId> xoá hẳn 1 edit (thư mục edits/<id>)
+ voices [--json] liệt kê giọng có sẵn + "Giọng của tôi" (giọng nhân bản, id vc-…)
+ voice-add <file> --name "Tên" --consent [--text "lời đoạn mẫu"] [--json]
+ nhân bản giọng từ 1 file (wav/mp3/m4a/ogg/webm, 10 giây – 3 phút, ≤ 30 MB).
+ --consent: xác nhận đây là giọng của bạn, hoặc bạn được người đó cho phép dùng.
+ Lưu ở ~/.lumreels/voices/<id>/ (đổi bằng LUMREELS_VOICES_DIR). Dùng: make … --voice <id>
+ voice-rename <id> "Tên" · voice-rm <id>`);
}
const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);
@@ -164,6 +172,42 @@ ${res.warnings.length} cảnh báo âm thanh (xem trên)` : ''}`);
console.log('Giọng: ' + o.voices.map((v) => v.id).join(', '));
if (o.hint) console.log(o.hint);
}
+ } else if (['voices', 'voice-add', 'voice-rm', 'voice-rename'].includes(cmd)) {
+ const S = await import('./engine/audio/voice-store.mjs');
+ if (cmd === 'voices') {
+ const { audioOptions } = await import('./engine/audio/prefs.mjs');
+ const mine = S.listClones().map(S.cloneView);
+ const preset = audioOptions().voices.filter((v) => v.engine && !v.mine);
+ if (opt.json) out({ mine, preset: preset.map((v) => ({ id: v.id, name: v.name, engine: v.engine, lang: v.lang })) });
+ else {
+ console.log(`Giọng của tôi (${mine.length}) — lưu ở ${S.VOICES_DIR}`);
+ for (const c of mine) console.log(` ${c.id} ${c.status.padEnd(10)} ${c.name}${c.refText ? ` · mẫu: "${c.refText.slice(0, 60)}"` : ''}${c.error ? ' · lỗi: ' + c.error : ''}`);
+ if (!mine.length) console.log(' (chưa có) — node cli.mjs voice-add <file> --name "Tên" --consent');
+ console.log('Giọng có sẵn: ' + preset.map((v) => v.id).join(', '));
+ }
+ } else if (cmd === 'voice-add') {
+ if (!pos[0] || typeof opt.name !== 'string') { usage(); process.exit(2); }
+ if (!opt.consent) { console.error('Lỗi: thêm --consent để xác nhận đây là giọng của bạn, hoặc bạn được người đó cho phép dùng'); process.exit(2); }
+ const C = await import('./engine/audio/voice-clone.mjs');
+ if (!C.cloneSupport().vieneu) { console.error('Lỗi: máy chưa có VieNeu-TTS (pip install vieneu)'); process.exit(1); }
+ const log = opt.json ? () => {} : console.log;
+ const meta = await C.prepareClone({ src: pos[0], filename: pos[0], name: opt.name, consent: true, refText: typeof opt.text === 'string' ? opt.text : undefined });
+ log(`giọng ${meta.id}: đoạn mẫu ${meta.ref.durS}s từ giây ${meta.ref.startS} (file ${meta.source.durS}s). Đang chép lời + mã hoá + đọc câu nghe thử…`);
+ const done = await C.finishClone(meta.id, { log });
+ const v = S.cloneView(done);
+ if (opt.json) out({ ...v, dir: S.cloneDir(meta.id) });
+ else console.log(done?.status === 'ready' ? `Xong: ${v.id} "${v.name}"\nNghe thử: ${path.join(S.cloneDir(v.id), 'sample.wav')}\nDùng: node cli.mjs make --template <id> --content … --voice ${v.id}` : 'Lỗi: ' + (done?.error || 'không rõ'));
+ process.exit(done?.status === 'ready' ? 0 : 1);
+ } else if (cmd === 'voice-rename') {
+ if (!pos[0] || !pos[1]) { usage(); process.exit(2); }
+ const m = S.renameClone(pos[0], pos.slice(1).join(' '));
+ console.log(`đã đổi tên ${m.id} → ${m.name}`);
+ } else {
+ if (!pos[0]) { usage(); process.exit(2); }
+ S.deleteClone(pos[0]);
+ console.log('đã xoá giọng ' + pos[0]);
+ }
+ process.exit(0);
} else if (cmd === 'run') {
// Chạy trọn 1 job (sinh cảnh theo chế độ + render). MCP dùng lệnh này ở tiến trình tách riêng.
if (!pos[0]) { usage(); process.exit(2); }
diff --git a/edit/http.mjs b/edit/http.mjs
index 2f4ba05..05a6c65 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -38,9 +38,9 @@ function synthMusicFile(id, styleName) {
* Đọc multipart/form-data theo luồng (file ghi thẳng ra đĩa, không giữ trong RAM).
* Bộ đệm luôn nhỏ: trước dấu phân cách đầu ≤ 64 KB, đầu mỗi phần ≤ 16 KB, trường chữ ≤ 64 KB, sau dấu kết thúc ≤ 64 KB;
* trong thân file chỉ giữ lại đuôi đủ dài để bắt dấu phân cách bị cắt ngang 2 chunk (không nối dồn → chi phí tuyến tính).
- * fileTarget(field, filename) → đường dẫn | null (bỏ qua) | throw (từ chối). Tổng ≤ maxBytes.
+ * fileTarget(field, filename) → đường dẫn | null (bỏ qua) | throw (từ chối). Tổng ≤ maxBytes (vượt → 413 tooBig).
*/
-export function parseMultipart(req, { maxBytes, fileTarget }) {
+export function parseMultipart(req, { maxBytes, fileTarget, tooBig = `file quá lớn (tối đa ${Math.round(MAX_UPLOAD / 1024 ** 3)} GB)` }) {
return new Promise((resolve, reject) => {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(req.headers['content-type'] || '');
if (!m) return reject(httpErr(400, 'thiếu boundary multipart'));
@@ -90,7 +90,7 @@ export function parseMultipart(req, { maxBytes, fileTarget }) {
cur = { name, filename, text: null, stream: null, size: 0 };
if (filename !== undefined) {
if (files[name]) throw httpErr(400, `trường ${name} gửi 2 lần`);
- const target = filename ? fileTarget(name, filename) : null;
+ const target = filename ? fileTarget(name, filename, fields) : null; // fields: các trường chữ đã gửi trước file
if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); opened.push(cur.stream); cur.stream.on('error', fail); }
} else cur.text = '';
state = 'body';
@@ -101,7 +101,7 @@ export function parseMultipart(req, { maxBytes, fileTarget }) {
if (failed) return;
total += chunk.length;
try {
- if (total > maxBytes) throw httpErr(413, `file quá lớn (tối đa ${Math.round(MAX_UPLOAD / 1024 ** 3)} GB)`);
+ if (total > maxBytes) throw httpErr(413, tooBig);
if (state === 'end') { epilogue += chunk.length; if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
buf = buf.length ? Buffer.concat([buf, chunk]) : chunk; // buf ≤ 64 KB + chunk ở mọi trạng thái
pump();
@@ -118,14 +118,14 @@ export function parseMultipart(req, { maxBytes, fileTarget }) {
});
}
-const originOk = (req, allowedHosts) => {
+export const originOk = (req, allowedHosts) => {
const o = req.headers.origin;
if (!o) return true; // curl/agent cục bộ không gửi Origin
try { return allowedHosts.has(new URL(o).host.toLowerCase()); } catch { return false; }
};
/** Trả lỗi rồi đóng kết nối (không đọc nốt phần thân còn lại của upload hỏng). */
-function sendAndClose(res, req, send, code, body) {
+export function sendAndClose(res, req, send, code, body) {
res.setHeader('Connection', 'close');
res.on('finish', () => req.destroy());
send(res, code, body);
diff --git a/engine/audio/prefs.mjs b/engine/audio/prefs.mjs
index 1e403bb..2dbccbf 100644
--- a/engine/audio/prefs.mjs
+++ b/engine/audio/prefs.mjs
@@ -4,6 +4,7 @@
import { spawnSync } from 'node:child_process';
import { MUSIC_STYLES, MUSIC_LIST } from './music.mjs';
import { DEFAULT_VOICE, DEFAULT_VOICE_EN, voiceLang, detectLang, isKokoroVoice, edgeVoiceFor } from './voice.mjs';
+import { isCloneVoice, readClone, listClones } from './voice-store.mjs';
const PY = process.env.LUMREELS_PYTHON || 'python';
@@ -51,6 +52,8 @@ export const defaultVoiceFor = (lang) => (lang === 'en' ? DEFAULT_VOICE_EN : DEF
/** { engine, speaker, lang } cho 1 giá trị voice. VieNeu/Kokoro không có trên máy → rơi về edge-tts cùng ngôn ngữ, cùng giới. */
export function voiceEngine(voice) {
const lang = voiceLang(voice);
+ // giọng nhân bản (vc-…): chỉ VieNeu đọc được, và chỉ đọc tiếng Việt (Kokoro không nhân bản giọng)
+ if (isCloneVoice(voice)) return ttsAvailable().vieneu ? { engine: 'vieneu', speaker: voice, lang: 'vi', clone: true } : { engine: 'edge', speaker: edgeVoiceFor(voice), lang: 'vi' };
if (String(voice).startsWith('edge:')) return { engine: 'edge', speaker: voice.slice(5), lang };
if (/^[a-z]{2}-[A-Z]{2}-\w+Neural$/.test(voice)) return { engine: 'edge', speaker: voice, lang };
if (isKokoroVoice(voice)) return ttsAvailable().kokoro ? { engine: 'kokoro', speaker: voice, lang } : { engine: 'edge', speaker: edgeVoiceFor(voice), lang };
@@ -68,6 +71,13 @@ export function normalizeAudioPrefs(a) {
const music = String(a.music ?? 'auto').trim() || 'auto';
if (!['auto', 'none', ...MUSIC_STYLES].includes(music)) throw new Error(`audio.music "${music}" không có (auto | none | ${MUSIC_STYLES.join(' | ')})`);
const voice = String(a.voice ?? 'auto').trim() || 'auto';
+ if (isCloneVoice(voice)) {
+ const c = readClone(voice);
+ if (!c) throw new Error(`audio.voice "${voice}": không có giọng nhân bản này (đã xoá?). Xem: node cli.mjs voices`);
+ if (c.status !== 'ready') throw new Error(`audio.voice "${voice}" (${c.name}): giọng nhân bản chưa sẵn sàng (${c.status})`);
+ const sfx = a.sfx === undefined ? true : !(a.sfx === false || a.sfx === 'false' || a.sfx === 0 || a.sfx === '0');
+ return { music, voice, sfx };
+ }
const known = ['auto', 'none', ...VIENEU_VOICES.map((v) => v.id), ...KOKORO_VOICES.map((v) => v.id), ...EDGE_VOICES.map((v) => v.id)];
// ngoài danh sách vẫn nhận: giọng Kokoro khác (am_puck…) và mọi giọng edge-tts dạng edge:xx-XX-…Neural
if (!known.includes(voice) && !isKokoroVoice(voice) && !/^edge:[a-z]{2}-[A-Z]{2}-\w+Neural$/.test(voice)) {
@@ -109,6 +119,11 @@ export function applyAudioPrefs(spec, prefs) {
return out;
}
+/** Giọng nhân bản đã sẵn sàng → mục chọn giọng (nhóm "mine", đọc tiếng Việt bằng VieNeu). */
+export function cloneVoices() {
+ return listClones().filter((c) => c.status === 'ready').map((c) => ({ id: c.id, name: c.name, engine: 'vieneu', lang: 'vi', mine: true, style: 'giọng nhân bản' }));
+}
+
/** Danh sách cho UI / API. */
export function audioOptions() {
const t = ttsAvailable();
@@ -121,7 +136,7 @@ export function audioOptions() {
music: [{ id: 'auto', name: 'Tự chọn theo mẫu' }, { id: 'none', name: 'Không nhạc' }, ...MUSIC_LIST.map((m) => ({ id: m.name, name: m.name, desc: m.desc }))],
// giọng có `lang` ('vi' | 'en'): UI nhóm theo <optgroup>. "auto" = đoán ngôn ngữ từ nội dung (có dấu tiếng Việt → vi).
voices: [{ id: 'auto', name: 'Theo mẫu (chỉ đọc khi mẫu có lời)' }, { id: 'none', name: 'Không lời đọc' },
- ...(t.vieneu ? VIENEU_VOICES : []), ...edge('vi'), ...(t.kokoro ? KOKORO_VOICES : []), ...edge('en')],
+ ...(t.vieneu ? cloneVoices() : []), ...(t.vieneu ? VIENEU_VOICES : []), ...edge('vi'), ...(t.kokoro ? KOKORO_VOICES : []), ...edge('en')],
langs: [{ id: 'vi', name: 'Tiếng Việt' }, { id: 'en', name: 'English' }],
vieneu: t.vieneu, kokoro: t.kokoro, edgeTts: t.edge,
hint: hints.length ? hints.join(' · ') : null,
diff --git a/engine/audio/tts_vieneu.py b/engine/audio/tts_vieneu.py
index f6cd99d..0146ecb 100644
--- a/engine/audio/tts_vieneu.py
+++ b/engine/audio/tts_vieneu.py
@@ -2,25 +2,70 @@
python engine/audio/tts_vieneu.py <jobs.json>
jobs.json: [{"text": "...", "out": "đường/dẫn.wav", "voice": "Hải Đăng"}, ...]
+ Giọng nhân bản: thay "voice" bằng "clone": {"wav": "ref.wav", "npz": "ref.npz", "text": "lời đoạn mẫu"}.
+ - có ref.npz (speaker embedding + mã âm đã mã hoá sẵn) → dùng thẳng, không mã hoá lại;
+ - chưa có → encode_reference(ref.wav) rồi ghi ref.npz cho lần sau (VieNeu v3 Turbo trả (speaker_emb, codes));
+ - bản VieNeu không mã hoá kiểu đó → infer(ref_audio=wav, ref_text=text) mỗi câu.
In 1 dòng JSON mỗi câu xong: {"out": ..., "ok": true} hoặc {"out": ..., "ok": false, "error": ...}.
"""
import json
+import os
import sys
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+def load_clone(tts, c, cache):
+ """Giọng nhân bản → kwargs cho tts.infer (cache trong tiến trình theo đường dẫn ref.wav)."""
+ key = c["wav"]
+ if key in cache:
+ return cache[key]
+ import numpy as np
+
+ kw = None
+ npz = c.get("npz")
+ if npz and os.path.exists(npz):
+ try:
+ d = np.load(npz, allow_pickle=False)
+ kw = {"voice": {"speaker_emb": d["speaker_emb"], "codes": d["codes"] if int(d["has_codes"]) else None}}
+ except Exception: # noqa: BLE001 file hỏng → mã hoá lại
+ kw = None
+ if kw is None:
+ try:
+ enc = tts.encode_reference(c["wav"])
+ if isinstance(enc, tuple) and len(enc) == 2 and enc[0] is not None:
+ emb, codes = enc
+ emb = np.asarray(emb, dtype=np.float32)
+ codes_arr = np.zeros(0, dtype=np.int64) if codes is None else np.asarray(codes, dtype=np.int64)
+ if npz:
+ tmp = npz + ".tmp.npz"
+ np.savez(tmp, speaker_emb=emb, codes=codes_arr, has_codes=np.int8(codes is not None))
+ os.replace(tmp, npz)
+ kw = {"voice": {"speaker_emb": emb, "codes": None if codes is None else codes_arr}}
+ except Exception as e: # noqa: BLE001
+ print(json.dumps({"warn": f"encode_reference lỗi, dùng ref_audio: {e}"}, ensure_ascii=False), flush=True)
+ if kw is None:
+ kw = {"ref_audio": c["wav"], "ref_text": c.get("text") or None}
+ cache[key] = kw
+ return kw
+
+
def main():
with open(sys.argv[1], encoding="utf-8") as f:
jobs = json.load(f)
from vieneu import Vieneu
tts = Vieneu()
+ clones = {}
for j in jobs:
err = None
for _ in range(3): # VieNeu thỉnh thoảng lỗi, thử lại
try:
- tts.save(tts.infer(j["text"], voice=j.get("voice") or None), j["out"])
+ if j.get("clone"):
+ kw = load_clone(tts, j["clone"], clones)
+ else:
+ kw = {"voice": j.get("voice") or None}
+ tts.save(tts.infer(j["text"], **kw), j["out"])
err = None
break
except Exception as e: # noqa: BLE001
diff --git a/engine/audio/voice-clone.mjs b/engine/audio/voice-clone.mjs
new file mode 100644
index 0000000..1c8c985
--- /dev/null
+++ b/engine/audio/voice-clone.mjs
@@ -0,0 +1,218 @@
+// Tạo giọng nhân bản từ 1 file âm thanh người dùng tải lên / thu âm:
+// 1. prepareClone: ffmpeg → mono 48 kHz, kiểm 10 s – 3 phút, cắt im lặng, chọn đoạn sạch 8–15 s → ref.wav (nhanh, chạy trong request)
+// 2. finishClone: lời đoạn mẫu (whisper nếu máy có), VieNeu mã hoá tham chiếu (ref.npz) + đọc 1 câu nghe thử (sample.wav)
+// Kho file: voice-store.mjs. Đọc bằng giọng nhân bản: voice.mjs + tts_vieneu.py (voice = id "vc-…").
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { run } from '../lib.mjs';
+import { readWav, writeWav, normalizeRms } from './dsp.mjs';
+import { synthVoice } from './voice.mjs';
+import { ttsAvailable } from './prefs.mjs';
+import { venvPython, WHISPER_MODEL } from '../../edit/env.mjs';
+import { cloneDir, newCloneId, cleanName, cleanRefText, readClone, writeClone, VOICES_DIR } from './voice-store.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PY = process.env.LUMREELS_PYTHON || 'python';
+const SR = 48000;
+export const CLONE_LIMITS = { minS: 10, maxS: 180, maxBytes: 30 * 1024 * 1024, refMinS: 8, refMaxS: 15 };
+export const CLONE_EXT = new Set(['.wav', '.mp3', '.m4a', '.ogg', '.webm', '.oga', '.opus']);
+export const CLONE_SAMPLE_TEXT = 'Xin chào, đây là giọng nói của tôi được nhân bản ngay trên máy. Bạn nghe thử xem có giống không nhé.';
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+
+// ---------- whisper (tuỳ máy) ----------
+const hasModule = (py, m) => {
+ try { return spawnSync(py, ['-c', `import importlib.util,sys;sys.exit(0 if importlib.util.find_spec('${m}') else 1)`], { windowsHide: true, timeout: 20000 }).status === 0; } catch { return false; }
+};
+let whisperPy;
+/** Python có faster-whisper: edit/.venv (LumReels Edit) trước, rồi Python của máy. null = không có. */
+export function whisperPython() {
+ if (whisperPy !== undefined) return whisperPy;
+ const cands = [venvPython(), PY].filter((p, i, a) => a.indexOf(p) === i && (p === PY || fs.existsSync(p)));
+ whisperPy = cands.find((p) => hasModule(p, 'faster_whisper')) || null;
+ return whisperPy;
+}
+/** Chép lời 1 file (tiếng Việt mặc định). Trả {text, device} hoặc null khi máy không có whisper / lỗi. */
+export async function transcribe(file, { lang = 'vi', log = () => {} } = {}) {
+ const py = whisperPython();
+ if (!py) return null;
+ const model = process.env.LUMREELS_WHISPER || WHISPER_MODEL;
+ const r = await run(py, ['-X', 'utf8', path.join(HERE, 'whisper_ref.py'), file, model, lang], { env: { ...process.env, PYTHONIOENCODING: 'utf-8', HF_HUB_DISABLE_TELEMETRY: '1' }, timeoutMs: 10 * 60 * 1000 });
+ const line = r.out.split(/\r?\n/).reverse().find((l) => l.startsWith('{"ok"'));
+ try {
+ const j = JSON.parse(line);
+ if (j.ok) return { text: j.text, device: j.device };
+ log('whisper lỗi: ' + String(j.error).slice(0, 300));
+ } catch { log('whisper lỗi: ' + r.out.trim().split(/\r?\n/).slice(-2).join(' ').slice(0, 300)); }
+ return null;
+}
+
+/** Chỗ có tiếng người nói [[giây đầu, giây cuối], …] bằng Silero VAD (đi kèm faster-whisper). null = máy không có / lỗi. */
+export async function detectSpeech(file) {
+ const py = whisperPython();
+ if (!py) return null;
+ const r = await run(py, ['-X', 'utf8', path.join(HERE, 'whisper_ref.py'), '--vad', file], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, timeoutMs: 120000 });
+ try { const j = JSON.parse(r.out.split(/\r?\n/).reverse().find((l) => l.startsWith('{"ok"'))); return j.ok ? j.speech : null; } catch { return null; }
+}
+
+// ---------- chọn đoạn mẫu ----------
+const FR = Math.round(0.02 * SR); // khung 20 ms
+/** Năng lượng từng khung (dBFS) + đỉnh. */
+function frames(x) {
+ const n = Math.floor(x.length / FR), db = new Float32Array(n), peak = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ let s = 0, p = 0;
+ for (let j = i * FR; j < (i + 1) * FR; j++) { const v = x[j]; s += v * v; const a = v < 0 ? -v : v; if (a > p) p = a; }
+ db[i] = 10 * Math.log10(s / FR + 1e-12); peak[i] = p;
+ }
+ return { db, peak, n };
+}
+const pct = (arr, q) => { const a = Array.from(arr).sort((p, r) => p - r); return a[Math.min(a.length - 1, Math.floor(q * a.length))]; };
+
+/**
+ * Chọn đoạn sạch nhất dài 8–15 s (ưu tiên ~10–12 s): nhiều tiếng nói, ít khoảng lặng dài, không vỡ tiếng,
+ * bắt đầu/kết thúc ở chỗ ngắt hơi. 8 s đầu càng dày tiếng nói càng tốt (VieNeu chỉ học 8 s đầu).
+ * speech: kết quả VAD (nếu có) — khi đó chỉ khung nằm trong đoạn nói mới tính là tiếng nói (nhạc nền/nhạc chuyển cảnh
+ * to cỡ nào cũng không bị chọn). Không có VAD thì dựa vào năng lượng.
+ * Trả {startS, endS, speechS, by: 'vad'|'energy'} theo giây trong x.
+ */
+export function pickSegment(x, speech = null) {
+ const { db, peak, n } = frames(x);
+ if (!n) throw httpErr(422, 'File âm thanh trống');
+ const floor = pct(db, 0.1), loud = pct(db, 0.95);
+ const th = Math.max(floor + Math.max(6, 0.3 * (loud - floor)), -55);
+ const voiced = Array.from(db, (d) => d > th);
+ if (speech?.length) {
+ const inSpeech = new Uint8Array(n);
+ for (const [a, b] of speech) for (let i = Math.max(0, Math.floor(a / 0.02)); i < Math.min(n, Math.ceil(b / 0.02)); i++) inSpeech[i] = 1;
+ for (let i = 0; i < n; i++) voiced[i] = voiced[i] && inSpeech[i] === 1;
+ }
+ // nối khe ngắn < 120 ms (giữa các âm tiết) để không coi là khoảng lặng
+ for (let i = 0, gap = 0; i < n; i++) {
+ if (!voiced[i]) gap++;
+ else { if (gap > 0 && gap <= 6 && i - gap - 1 >= 0 && voiced[i - gap - 1]) for (let k = i - gap; k < i; k++) voiced[k] = true; gap = 0; }
+ }
+ const speechS = voiced.filter(Boolean).length * 0.02;
+ if (speechS < CLONE_LIMITS.refMinS) throw httpErr(422, `File có quá ít tiếng nói (nghe ra ${speechS.toFixed(1)} s, cần ≥ ${CLONE_LIMITS.refMinS} s nói rõ). Thu lại ở chỗ yên tĩnh, nói liền mạch.`);
+ // tổng tiền tố để tính nhanh
+ const cv = new Int32Array(n + 1), cc = new Int32Array(n + 1);
+ for (let i = 0; i < n; i++) { cv[i + 1] = cv[i] + (voiced[i] ? 1 : 0); cc[i + 1] = cc[i] + (peak[i] > 0.985 ? 1 : 0); }
+ const onsets = [], offsets = [];
+ for (let i = 0; i < n; i++) {
+ if (voiced[i] && (i === 0 || !voiced[i - 1])) onsets.push(i);
+ if (voiced[i] && (i === n - 1 || !voiced[i + 1])) offsets.push(i + 1);
+ }
+ const minF = CLONE_LIMITS.refMinS / 0.02, maxF = CLONE_LIMITS.refMaxS / 0.02, head = 8 / 0.02;
+ const longPause = (a, b) => { // tổng giây của các khoảng lặng > 0,6 s trong [a, b)
+ let tot = 0, run0 = 0;
+ for (let i = a; i < b; i++) { if (!voiced[i]) run0++; else { if (run0 > 30) tot += run0 * 0.02; run0 = 0; } }
+ return tot;
+ };
+ let best = null;
+ const score = (a, b) => {
+ const L = b - a, vr = (cv[b] - cv[a]) / L, hr = (cv[Math.min(b, a + head)] - cv[a]) / Math.min(L, head);
+ const clip = (cc[b] - cc[a]) / L;
+ const sLen = L * 0.02;
+ return vr + 0.6 * hr - 4 * clip - 0.08 * longPause(a, b) - 0.01 * Math.abs(sLen - 11);
+ };
+ for (const a of onsets) {
+ for (const b of offsets) {
+ if (b - a < minF) continue;
+ if (b - a > maxF) break;
+ const s = score(a, b);
+ if (!best || s > best.s) best = { a, b, s };
+ }
+ }
+ if (!best) {
+ // nói liền không ngắt hơi đủ chỗ: cửa sổ trượt 11 s (hoặc cả đoạn nếu ngắn hơn)
+ const L = Math.min(n, Math.round(11 / 0.02));
+ for (let a = 0; a + L <= n; a += 25) { const s = score(a, a + L); if (!best || s > best.s) best = { a, b: a + L, s }; }
+ }
+ return { startS: best.a * 0.02, endS: best.b * 0.02, speechS, by: speech?.length ? 'vad' : 'energy' };
+}
+
+// ---------- 1. nhận file ----------
+/**
+ * Đổi file về mono 48 kHz, kiểm độ dài, chọn đoạn mẫu → ref.wav. Lỗi đầu vào → throw có .code (4xx).
+ * src: file đã tải lên (sẽ bị xoá sau khi xử lý). Trả meta (status "processing").
+ */
+export async function prepareClone({ src, filename, name, consent, refText, id = newCloneId() }) {
+ const nm = cleanName(name);
+ if (!(consent === true || consent === '1' || consent === 'true' || consent === 'on')) throw httpErr(400, 'Cần tick xác nhận: đây là giọng của bạn, hoặc bạn được người đó cho phép dùng');
+ const ext = path.extname(String(filename || src)).toLowerCase();
+ if (!CLONE_EXT.has(ext)) throw httpErr(415, `Định dạng ${ext || '?'} chưa hỗ trợ (wav, mp3, m4a, ogg, webm)`);
+ const st = fs.statSync(src);
+ if (st.size > CLONE_LIMITS.maxBytes) throw httpErr(413, 'File quá lớn (tối đa 30 MB)');
+ const text = cleanRefText(refText);
+ const dir = cloneDir(id);
+ fs.mkdirSync(dir, { recursive: true });
+ const full = path.join(dir, 'full.wav');
+ try {
+ // highpass bỏ ù nền; giới hạn đọc 200 s (file dài hơn 3 phút là bị từ chối)
+ const r = await run('ffmpeg', ['-y', '-v', 'error', '-i', src, '-t', '200', '-vn', '-ac', '1', '-ar', String(SR), '-af', 'highpass=f=70', '-c:a', 'pcm_s16le', full], { timeoutMs: 120000 });
+ if (r.code !== 0 || !fs.existsSync(full)) throw httpErr(415, 'Không đọc được file âm thanh (file hỏng hoặc không phải âm thanh)');
+ const x = readWav(full).chans[0];
+ const durS = x.length / SR;
+ if (durS < CLONE_LIMITS.minS) throw httpErr(422, `File ngắn quá (${durS.toFixed(1)} s). Cần 10 giây – 3 phút.`);
+ if (durS > CLONE_LIMITS.maxS + 0.5) throw httpErr(422, 'File dài quá (hơn 3 phút). Cắt bớt còn 10 giây – 3 phút.');
+ const seg = pickSegment(x, await detectSpeech(full));
+ const pad = Math.round(0.08 * SR);
+ const a = Math.max(0, Math.round(seg.startS * SR) - pad), b = Math.min(x.length, Math.round(seg.endS * SR) + pad);
+ const y = x.slice(a, b);
+ const f = Math.round(0.01 * SR);
+ for (let i = 0; i < f; i++) { y[i] *= i / f; y[y.length - 1 - i] *= i / f; }
+ normalizeRms([y], -20, -1);
+ writeWav(path.join(dir, 'ref.wav'), [y], SR);
+ if (text) fs.writeFileSync(path.join(dir, 'ref.txt'), text + '\n');
+ const refHash = crypto.createHash('sha1').update(fs.readFileSync(path.join(dir, 'ref.wav'))).digest('hex').slice(0, 12);
+ return writeClone(id, {
+ name: nm, status: 'processing', step: 'queued', error: null, createdAt: new Date().toISOString(), refHash,
+ source: { filename: path.basename(String(filename || '')).slice(0, 120), bytes: st.size, durS: +durS.toFixed(2) },
+ ref: { startS: +(a / SR).toFixed(2), durS: +(y.length / SR).toFixed(2), speechS: +seg.speechS.toFixed(1), by: seg.by },
+ refText: text, refTextSource: text ? 'user' : null,
+ consent: { at: new Date().toISOString(), text: 'Đây là giọng của tôi, hoặc tôi được người đó cho phép dùng' },
+ });
+ } catch (e) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ throw e;
+ } finally {
+ fs.rmSync(full, { force: true });
+ }
+}
+
+// ---------- 2. lời mẫu + mã hoá + câu nghe thử ----------
+export const activeClones = new Set();
+/** Chạy nền sau prepareClone. Không throw: lỗi ghi vào meta (status "error"). */
+export async function finishClone(id, { log = () => {} } = {}) {
+ activeClones.add(id);
+ const dir = cloneDir(id);
+ try {
+ const m = readClone(id);
+ if (!m) throw new Error('không thấy giọng');
+ if (!m.refText) {
+ writeClone(id, { step: 'transcribe' });
+ const t = await transcribe(path.join(dir, 'ref.wav'), { log });
+ if (t?.text) { fs.writeFileSync(path.join(dir, 'ref.txt'), t.text + '\n'); writeClone(id, { refText: t.text, refTextSource: 'whisper' }); log(`giọng ${id}: lời mẫu (whisper ${t.device}): ${t.text}`); }
+ }
+ writeClone(id, { step: 'encode' });
+ const cache = path.join(dir, 'cache');
+ const [r] = await synthVoice([{ t: 0, text: CLONE_SAMPLE_TEXT }], cache, { engine: 'vieneu', voice: id, fallback: false, log });
+ fs.copyFileSync(r.file, path.join(dir, 'sample.wav'));
+ fs.rmSync(cache, { recursive: true, force: true });
+ if (!fs.existsSync(path.join(dir, 'ref.npz'))) log(`giọng ${id}: VieNeu không mã hoá sẵn được tham chiếu, mỗi lần đọc sẽ mã hoá lại (chậm hơn chút)`);
+ return writeClone(id, { status: 'ready', step: null, error: null, encoded: fs.existsSync(path.join(dir, 'ref.npz')) });
+ } catch (e) {
+ log(`giọng ${id} lỗi: ${e.message}`);
+ if (fs.existsSync(dir)) return writeClone(id, { status: 'error', step: null, error: String(e.message).slice(0, 400) });
+ return null;
+ } finally {
+ activeClones.delete(id);
+ }
+}
+
+/** Đủ để tạo giọng nhân bản không (VieNeu trên máy). */
+export function cloneSupport() {
+ return { vieneu: ttsAvailable().vieneu, whisper: !!whisperPython(), dir: VOICES_DIR };
+}
diff --git a/engine/audio/voice-store.mjs b/engine/audio/voice-store.mjs
new file mode 100644
index 0000000..58e7f98
--- /dev/null
+++ b/engine/audio/voice-store.mjs
@@ -0,0 +1,114 @@
+// Kho "Giọng của tôi" (giọng nhân bản): mỗi giọng 1 thư mục ngoài repo, mặc định ~/.lumreels/voices/<id>/
+// meta.json tên, trạng thái (processing | ready | error), đoạn mẫu đã chọn, xác nhận quyền dùng giọng
+// ref.wav đoạn mẫu sạch 8–15 s, mono 48 kHz (VieNeu v3 Turbo lấy 8 s đầu để học giọng)
+// ref.npz tham chiếu đã mã hoá sẵn (speaker embedding + mã âm), tts_vieneu.py tự ghi lần đầu dùng
+// ref.txt lời của đoạn mẫu (whisper chép, hoặc người dùng gõ). v3 Turbo không cần, giữ cho bản VieNeu khác
+// sample.wav câu nghe thử
+// Đổi chỗ lưu: LUMREELS_VOICES_DIR. Module này chỉ đọc/ghi file, không gọi mô hình (xem voice-clone.mjs).
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import crypto from 'node:crypto';
+
+export const VOICES_DIR = process.env.LUMREELS_VOICES_DIR || path.join(os.homedir(), '.lumreels', 'voices');
+/** Id giọng nhân bản: "vc-" + 8 hex. Chỉ dạng này mới thành đường dẫn (không lọt ../). */
+export const CLONE_ID_RE = /^vc-[a-f0-9]{8}$/;
+export const isCloneVoice = (v) => CLONE_ID_RE.test(String(v || ''));
+export const NAME_MAX = 40;
+
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+
+export function cloneDir(id) {
+ if (!isCloneVoice(id)) throw httpErr(400, 'id giọng không hợp lệ');
+ return path.join(VOICES_DIR, id);
+}
+export function newCloneId() {
+ for (;;) {
+ const id = 'vc-' + crypto.randomBytes(4).toString('hex');
+ if (!fs.existsSync(path.join(VOICES_DIR, id))) return id;
+ }
+}
+
+/** Tên giọng: bỏ khoảng trắng thừa + ký tự điều khiển, 1–40 ký tự. */
+export function cleanName(name) {
+ const s = String(name ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
+ if (!s) throw httpErr(400, 'Đặt tên cho giọng (1–40 ký tự)');
+ if ([...s].length > NAME_MAX) throw httpErr(400, `Tên giọng tối đa ${NAME_MAX} ký tự`);
+ return s;
+}
+/** Lời đoạn mẫu người dùng gõ: tối đa 600 ký tự. Trống → null. */
+export function cleanRefText(t) {
+ const s = String(t ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
+ if (s.length > 600) throw httpErr(400, 'Lời đoạn mẫu tối đa 600 ký tự');
+ return s || null;
+}
+
+export function readClone(id) {
+ if (!isCloneVoice(id)) return null;
+ try { return JSON.parse(fs.readFileSync(path.join(VOICES_DIR, id, 'meta.json'), 'utf8')); } catch { return null; }
+}
+export function writeClone(id, patch) {
+ const dir = cloneDir(id);
+ fs.mkdirSync(dir, { recursive: true });
+ const cur = readClone(id) || {};
+ const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
+ const f = path.join(dir, 'meta.json');
+ fs.writeFileSync(f + '.tmp', JSON.stringify(next, null, 2));
+ fs.renameSync(f + '.tmp', f);
+ return next;
+}
+
+/** Danh sách giọng (mới trước). */
+export function listClones() {
+ let ids = [];
+ try { ids = fs.readdirSync(VOICES_DIR).filter((d) => CLONE_ID_RE.test(d)); } catch { return []; }
+ return ids.map(readClone).filter(Boolean).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
+}
+export const cloneReady = (id) => readClone(id)?.status === 'ready';
+
+/** Đường dẫn tham chiếu cho TTS. Giọng chưa xong / đã xoá → lỗi rõ ràng. */
+export function cloneRef(id) {
+ const m = readClone(id);
+ if (!m) throw new Error(`Giọng nhân bản "${id}" không còn (đã xoá?). Chọn giọng khác.`);
+ const dir = cloneDir(id);
+ const wav = path.join(dir, 'ref.wav');
+ if (!fs.existsSync(wav)) throw new Error(`Giọng "${m.name}" chưa có đoạn mẫu (đang xử lý hoặc lỗi).`);
+ const txt = path.join(dir, 'ref.txt');
+ return { id, name: m.name, wav, npz: path.join(dir, 'ref.npz'), text: fs.existsSync(txt) ? fs.readFileSync(txt, 'utf8').trim() : '', stamp: m.refHash || m.createdAt };
+}
+
+export function renameClone(id, name) {
+ if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
+ return writeClone(id, { name: cleanName(name) });
+}
+export function setRefText(id, text) {
+ if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
+ const t = cleanRefText(text);
+ const f = path.join(cloneDir(id), 'ref.txt');
+ if (t) fs.writeFileSync(f, t + '\n'); else fs.rmSync(f, { force: true });
+ return writeClone(id, { refText: t, refTextSource: t ? 'user' : null });
+}
+export function deleteClone(id) {
+ if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
+ fs.rmSync(cloneDir(id), { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+}
+
+/** Giọng đang "processing" khi tiến trình đã tắt → lỗi, để người dùng tải lại. */
+export function markStaleClones(activeIds = new Set()) {
+ for (const c of listClones()) {
+ if (c.status === 'processing' && !activeIds.has(c.id)) writeClone(c.id, { status: 'error', error: 'Bị ngắt giữa chừng (app tắt). Xoá rồi tải lại file.' });
+ }
+}
+
+/** Dạng gửi cho UI/API (không lộ đường dẫn máy). */
+export function cloneView(m) {
+ if (!m) return null;
+ const has = (f) => fs.existsSync(path.join(VOICES_DIR, m.id, f));
+ return {
+ id: m.id, name: m.name, status: m.status, step: m.step || null, error: m.error || null, createdAt: m.createdAt, updatedAt: m.updatedAt,
+ refText: m.refText || null, refTextSource: m.refTextSource || null, ref: m.ref || null, sourceDurS: m.source?.durS ?? null,
+ lang: 'vi',
+ sample: has('sample.wav') ? `/api/voices/mine/${m.id}/sample.wav` : null,
+ refAudio: has('ref.wav') ? `/api/voices/mine/${m.id}/ref.wav` : null,
+ };
+}
diff --git a/engine/audio/voice.mjs b/engine/audio/voice.mjs
index 43ee36d..c0d7b33 100644
--- a/engine/audio/voice.mjs
+++ b/engine/audio/voice.mjs
@@ -7,6 +7,7 @@ import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { run } from '../lib.mjs';
import { readWav, writeWav, normalizeRms, SR } from './dsp.mjs';
+import { isCloneVoice, cloneRef } from './voice-store.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
export const DEFAULT_VOICE = 'Hải Đăng';
@@ -141,7 +142,8 @@ function trimNormalize(file) {
/**
* lines: [{t, text, say?}] → [{t, text, file, dur}]. workDir chứa cache voice-<hash>.wav.
- * engine: 'vieneu' | 'kokoro' | 'edge'. Lỗi VieNeu/Kokoro thì tự chuyển edge-tts (cùng ngôn ngữ, cùng giới).
+ * engine: 'vieneu' | 'kokoro' | 'edge'. Lỗi VieNeu/Kokoro thì tự chuyển edge-tts (cùng ngôn ngữ, cùng giới),
+ * trừ khi fallback = false (khi đó throw). voice "vc-…" = giọng nhân bản (VieNeu đọc theo ref.wav / ref.npz).
*/
// Mỗi lúc chỉ 1 lượt TTS (VieNeu/Kokoro nạp mô hình nặng): xếp hàng trong tiến trình.
let ttsChain = Promise.resolve();
@@ -150,23 +152,27 @@ export function synthVoice(...args) {
ttsChain = p.catch(() => {});
return p;
}
-async function synthVoiceNow(lines, workDir, { engine = 'vieneu', voice = DEFAULT_VOICE, log = console.log } = {}) {
+async function synthVoiceNow(lines, workDir, { engine = 'vieneu', voice = DEFAULT_VOICE, log = console.log, fallback = true } = {}) {
fs.mkdirSync(workDir, { recursive: true });
if (engine === 'vieneu' && isKokoroVoice(voice)) engine = 'kokoro';
+ // giọng nhân bản: lỗi rõ ràng nếu đã xoá; cache theo cả đoạn mẫu (refHash)
+ const clone = engine === 'vieneu' && isCloneVoice(voice) ? cloneRef(voice) : null;
+ if (isCloneVoice(voice) && engine === 'edge') log(`CẢNH BÁO: máy không có VieNeu, giọng nhân bản "${voice}" đọc tạm bằng edge-tts (không giống giọng gốc)`);
const lang = voiceLang(voice);
const items = lines.map((l) => {
const spoken = toSpeech(l.say || l.text, lang);
- const h = crypto.createHash('sha1').update(`${engine}|${voice}|${spoken}`).digest('hex').slice(0, 12);
+ const h = crypto.createHash('sha1').update(`${engine}|${voice}${clone ? '|' + clone.stamp : ''}|${spoken}`).digest('hex').slice(0, 12);
return { ...l, spoken, file: path.join(workDir, `voice-${h}.wav`) };
});
const todo = items.filter((it) => !fs.existsSync(it.file));
const LOCAL = { vieneu: ['VieNeu', 'tts_vieneu.py'], kokoro: ['Kokoro', 'tts_kokoro.py'] }[engine];
if (todo.length && LOCAL) {
const [label, script] = LOCAL;
- const raw = todo.map((it) => ({ text: it.spoken, voice, out: it.file.replace(/\.wav$/, '.raw.wav') }));
+ const raw = todo.map((it) => ({ text: it.spoken, voice: clone ? null : voice, out: it.file.replace(/\.wav$/, '.raw.wav'),
+ ...(clone ? { clone: { wav: clone.wav, npz: clone.npz, text: clone.text } } : {}) }));
const jf = path.join(workDir, 'tts-jobs.json');
fs.writeFileSync(jf, JSON.stringify(raw, null, 1));
- log(`giọng: ${label} "${voice}" đọc ${todo.length} câu (nạp mô hình lần đầu hơi lâu)…`);
+ log(`giọng: ${label} "${clone ? clone.name + ' (nhân bản ' + voice + ')' : voice}" đọc ${todo.length} câu (nạp mô hình lần đầu hơi lâu)…`);
const r = await run(PY, [path.join(HERE, script), jf], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
let miss = 0;
for (let i = 0; i < todo.length; i++) {
@@ -174,10 +180,12 @@ async function synthVoiceNow(lines, workDir, { engine = 'vieneu', voice = DEFAUL
}
if (r.code !== 0 || miss) {
const errs = r.out.split(/\r?\n/).filter((l) => l.includes('"ok": false')).slice(-1).map((l) => l.slice(0, 300)).join(' ');
+ if (!fallback) throw new Error(`${label} lỗi${miss ? ` (${miss}/${todo.length} câu)` : ''}: ` + (errs || r.out.trim().split(/\r?\n/).slice(-3).join(' ').slice(0, 400)));
log(`CẢNH BÁO: ${label} lỗi${miss ? ` (${miss}/${todo.length} câu)` : ''}, chuyển edge-tts. ` + (errs || r.out.trim().split(/\r?\n/).pop().slice(0, 300)));
}
}
for (const it of items.filter((x) => !fs.existsSync(x.file))) {
+ if (!fallback) throw new Error(`Không tạo được giọng đọc ${engine} cho "${it.spoken}"`);
const ev = edgeVoiceFor(voice), mp3 = it.file.replace(/\.wav$/, '.mp3');
log(`giọng: edge-tts ${ev}: "${it.spoken}"`);
const r = await run(PY, ['-m', 'edge_tts', '--voice', ev, '--text', it.spoken, '--write-media', mp3], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
diff --git a/engine/audio/whisper_ref.py b/engine/audio/whisper_ref.py
new file mode 100644
index 0000000..df41f27
--- /dev/null
+++ b/engine/audio/whisper_ref.py
@@ -0,0 +1,62 @@
+"""Chép lời 1 file âm thanh ngắn bằng faster-whisper (dùng cho đoạn mẫu giọng nhân bản + tự nghe lại).
+
+ python engine/audio/whisper_ref.py <file.wav> [model] [lang]
+In 1 dòng JSON: {"ok": true, "text": "...", "device": "cuda|cpu", "logprob": -0.2} hoặc {"ok": false, "error": "..."}.
+Thử GPU trước, lỗi (thiếu CUDA/cuDNN) thì chạy CPU int8. Có bật VAD để không "nghe" ra chữ từ đoạn nhạc.
+
+ python engine/audio/whisper_ref.py --vad <file>
+Chỉ dò chỗ có tiếng người nói (Silero VAD đi kèm faster-whisper, nhanh, phân biệt được tiếng nói với nhạc nền):
+{"ok": true, "speech": [[giây_đầu, giây_cuối], ...]}.
+"""
+import json
+import sys
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+
+def run(path, model, lang, device, compute):
+ from faster_whisper import WhisperModel
+
+ m = WhisperModel(model, device=device, compute_type=compute)
+ segs, _info = m.transcribe(path, language=lang or None, beam_size=5, vad_filter=True, condition_on_previous_text=False)
+ segs = list(segs)
+ text = " ".join(s.text.strip() for s in segs).strip()
+ lp = sum(s.avg_logprob for s in segs) / len(segs) if segs else None
+ return text, lp
+
+
+def vad(path):
+ from faster_whisper import decode_audio
+ from faster_whisper.vad import VadOptions, get_speech_timestamps
+
+ sr = 16000
+ audio = decode_audio(path, sampling_rate=sr)
+ ts = get_speech_timestamps(audio, VadOptions(threshold=0.5, min_silence_duration_ms=250, speech_pad_ms=30), sampling_rate=sr)
+ print(json.dumps({"ok": True, "speech": [[round(t["start"] / sr, 3), round(t["end"] / sr, 3)] for t in ts]}), flush=True)
+
+
+def main():
+ if sys.argv[1] == "--vad":
+ try:
+ vad(sys.argv[2])
+ except Exception as e: # noqa: BLE001
+ print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False), flush=True)
+ sys.exit(1)
+ return
+ path = sys.argv[1]
+ model = sys.argv[2] if len(sys.argv) > 2 else "large-v3"
+ lang = sys.argv[3] if len(sys.argv) > 3 else "vi"
+ err = None
+ for device, compute in (("cuda", "float16"), ("cpu", "int8")):
+ try:
+ text, lp = run(path, model, lang, device, compute)
+ print(json.dumps({"ok": True, "text": text, "device": device, "logprob": lp}, ensure_ascii=False), flush=True)
+ return
+ except Exception as e: # noqa: BLE001
+ err = f"{device}: {e}"
+ print(json.dumps({"ok": False, "error": err}, ensure_ascii=False), flush=True)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/generator/prompt.mjs b/generator/prompt.mjs
index 19ac6d5..2a7c762 100644
--- a/generator/prompt.mjs
+++ b/generator/prompt.mjs
@@ -3,6 +3,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { detectLang, voiceLang, DEFAULT_VOICE_EN } from '../engine/audio/voice.mjs';
+import { isCloneVoice } from '../engine/audio/voice-store.mjs';
const fmt = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
@@ -18,7 +19,8 @@ function audioRule(a, content = '') {
if (a.sfx === false) r.push('KHÔNG tiếng động: `"sfx": []`');
if (a.voice === 'none') r.push('KHÔNG lời đọc: `"voice": null` (kể cả mẫu có narration)');
else if (a.voice && a.voice !== 'auto') r.push(`CÓ lời đọc (kể cả mẫu không có narration), \`"speaker": "${a.voice}"\`: 1–3 câu ngắn bám nội dung trên màn hình, câu cuối nói tên thương hiệu/CTA nếu có`);
- if (a.voice !== 'none' && lang === 'en') r.push(`lời đọc (nếu có) viết bằng TIẾNG ANH, ~2,7 từ/giây${a.voice === 'auto' || !a.voice ? `, \`"speaker": "${DEFAULT_VOICE_EN}"\`` : ''}`);
+ if (isCloneVoice(a.voice)) r.push('lời đọc viết bằng TIẾNG VIỆT (giọng nhân bản của người dùng chỉ đọc tiếng Việt), kể cả khi nội dung là tiếng Anh');
+ else if (a.voice !== 'none' && lang === 'en') r.push(`lời đọc (nếu có) viết bằng TIẾNG ANH, ~2,7 từ/giây${a.voice === 'auto' || !a.voice ? `, \`"speaker": "${DEFAULT_VOICE_EN}"\`` : ''}`);
return r.length ? ` - Người dùng đã chọn âm thanh: ${r.join('; ')}.
` : '';
}
diff --git a/mcp/server.mjs b/mcp/server.mjs
index 0e8a21c..b491299 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -18,11 +18,12 @@ import { rewriteScript } from '../generator/rewrite.mjs';
import { reAudio, listVersions, saveAudioSpec } from '../generator/audio-job.mjs';
import { MUSIC_STYLES } from '../engine/audio/music.mjs';
import { audioOptions } from '../engine/audio/prefs.mjs';
+import { listClones, cloneView, cloneDir } from '../engine/audio/voice-store.mjs';
import { createEdit, editView, editStyles, editReady, readEditJob, ID_RE as EDIT_ID_RE } from '../edit/jobs.mjs';
const audioSchema = z.object({
music: z.string().optional().describe(`auto | none | ${MUSIC_STYLES.join(' | ')}`),
- voice: z.string().optional().describe('auto | none | tên giọng (xem set_audio / audio-options), vd "Hải Đăng", "Trúc Ly", "edge:vi-VN-HoaiMyNeural"; tiếng Anh: "af_heart", "am_michael", "bf_emma", "edge:en-US-AvaMultilingualNeural". auto = đoán ngôn ngữ từ nội dung'),
+ voice: z.string().optional().describe('auto | none | tên giọng (xem set_audio / audio-options), vd "Hải Đăng", "Trúc Ly", "edge:vi-VN-HoaiMyNeural"; tiếng Anh: "af_heart", "am_michael", "bf_emma", "edge:en-US-AvaMultilingualNeural"; giọng nhân bản của người dùng: "vc-xxxxxxxx" (xem list_voices, chỉ đọc tiếng Việt). auto = đoán ngôn ngữ từ nội dung'),
sfx: z.boolean().optional(),
});
@@ -261,6 +262,23 @@ server.registerTool('list_jobs', {
inputSchema: { limit: z.number().int().min(1).max(100).default(20) },
}, async ({ limit }) => ({ content: [json(listJobs().slice(0, limit).map(jobSummary))] }));
+server.registerTool('list_voices', {
+ title: 'Danh sách giọng đọc',
+ description: [
+ 'Giọng đọc dùng được cho audio.voice: "mine" = giọng nhân bản người dùng đã tạo trong app (id vc-xxxxxxxx, VieNeu đọc, chỉ tiếng Việt;',
+ 'chọn cho nội dung tiếng Anh thì lời đọc được viết bằng tiếng Việt), "preset" = giọng có sẵn (VieNeu tiếng Việt, Kokoro tiếng Anh, edge-tts).',
+ 'Chỉ giọng status "ready" mới dùng được. Tạo giọng nhân bản: trong app (mục Giọng của tôi) hoặc node cli.mjs voice-add.',
+ ].join(' '),
+ inputSchema: {},
+}, async () => {
+ const o = audioOptions();
+ return { content: [json({
+ mine: listClones().map((c) => ({ ...cloneView(c), sample: c.status === 'ready' ? path.join(cloneDir(c.id), 'sample.wav') : null, refAudio: undefined })),
+ preset: o.voices.filter((v) => v.engine && !v.mine).map((v) => ({ id: v.id, name: v.name, engine: v.engine, lang: v.lang })),
+ hint: o.hint,
+ })] };
+});
+
// ---- Edit video của bạn (edit/) -----------------------------------------------------------------------------------
const editSummary = (id) => {
const v = editView(id, { withLog: true });
diff --git a/server/public/audio-panel.js b/server/public/audio-panel.js
index 2ad8206..9140bf1 100644
--- a/server/public/audio-panel.js
+++ b/server/public/audio-panel.js
@@ -12,7 +12,8 @@
document.head.appendChild(css);
let opts = null;
- const optsP = fetch('/api/audio/options').then((r) => r.json()).then((o) => (opts = o)).catch(() => null);
+ const loadOpts = () => fetch('/api/audio/options').then((r) => r.json()).then((o) => (opts = o)).catch(() => null);
+ const optsP = loadOpts();
// ---------- nghe thử (1 trình phát chung) ----------
const player = new Audio();
@@ -59,8 +60,12 @@
: v.lang === 'en' ? `${srv(v.name)} · ${srv(v.style)}` : `${v.name} · ${srv(v.gender)}, ${srv(v.region)} · ${srv(v.style)}`)}</option>`;
const allV = opts?.voices || [{ id: 'auto', name: 'Theo mẫu (chỉ đọc khi mẫu có lời)' }];
const langs = opts?.langs || [{ id: 'vi', name: 'Tiếng Việt' }, { id: 'en', name: 'English' }];
- const voices = allV.filter((v) => !v.engine).map(vOpt).join('') + langs.map((l) => {
- const vs = allV.filter((v) => v.engine && (v.lang || 'vi') === l.id);
+ // "Giọng của tôi" (giọng nhân bản, v.mine) đứng nhóm riêng, trước các nhóm ngôn ngữ
+ const mine = allV.filter((v) => v.mine);
+ const mineOpt = (v) => `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(v.name)} · ${esc(t('vc.optTag'))}</option>`;
+ const voices = allV.filter((v) => !v.engine).map(vOpt).join('')
+ + (mine.length ? `<optgroup label="${esc(t('vc.title'))}">${mine.map(mineOpt).join('')}</optgroup>` : '') + langs.map((l) => {
+ const vs = allV.filter((v) => v.engine && !v.mine && (v.lang || 'vi') === l.id);
return vs.length ? `<optgroup label="${esc(srv(l.name))}">${vs.map(vOpt).join('')}</optgroup>` : '';
}).join('');
return `
@@ -96,15 +101,36 @@
// ---------- (1) form dựng ----------
const mount = document.getElementById('audioPanel');
+ /** Vẽ lại form dựng với lựa chọn cur; gắn lại khối "Giọng của tôi" (voice-clone.js) ngay dưới ô giọng đọc. */
+ function renderMount(cur) {
+ mount.innerHTML = `<div class="ap-title">${esc(t('ap.title'))}</div>` + controlsHtml(cur);
+ attachVoices();
+ }
+ function attachVoices() {
+ const vc = window.LumVoices?.el;
+ if (!mount || !vc) return;
+ const row = $('[data-ap="voice"]', mount)?.closest('.ap-row');
+ if (row) row.after(vc);
+ }
if (mount) {
mount.classList.add('ap');
mount.innerHTML = `<div class="ap-title">${esc(t('ap.title'))}</div><div class="hint">${esc(t('ap.loadingOpts'))}</div>`;
- optsP.then(() => { mount.innerHTML = `<div class="ap-title">${esc(t('ap.title'))}</div>` + controlsHtml({ music: 'auto', voice: 'auto', sfx: true }); });
+ optsP.then(() => renderMount({ music: 'auto', voice: 'auto', sfx: true }));
wirePreview(mount);
}
window.LumAudio = {
/** Giá trị cho POST /api/jobs: { music, voice, sfx }. */
value: () => (mount && $('[data-ap="music"]', mount) ? readControls(mount) : undefined),
+ /** Tải lại danh sách giọng (sau khi thêm/xoá/đổi tên giọng nhân bản). selectVoice: chọn luôn giọng này. */
+ reload: async (selectVoice) => {
+ await loadOpts();
+ if (mount && $('[data-ap="music"]', mount)) {
+ const cur = readControls(mount);
+ if (selectVoice) cur.voice = selectVoice;
+ renderMount(cur);
+ }
+ },
+ attachVoices,
};
// ---------- (2) mỗi video đã dựng ----------
@@ -182,7 +208,7 @@
window.addEventListener('lumreels:lang', () => {
if (mount) {
const title = `<div class="ap-title">${esc(t('ap.title'))}</div>`;
- mount.innerHTML = $('[data-ap="music"]', mount) ? title + controlsHtml(readControls(mount)) : title + `<div class="hint">${esc(t('ap.loadingOpts'))}</div>`;
+ if ($('[data-ap="music"]', mount)) renderMount(readControls(mount)); else mount.innerHTML = title + `<div class="hint">${esc(t('ap.loadingOpts'))}</div>`;
}
document.querySelectorAll('details.ap-job').forEach((d) => {
const sum = $('summary', d); if (sum) sum.textContent = t('ap.summary');
diff --git a/server/public/i18n.js b/server/public/i18n.js
index ecb9c5d..0e28d30 100644
--- a/server/public/i18n.js
+++ b/server/public/i18n.js
@@ -200,6 +200,71 @@
'ap.loading': 'Đang tải…',
'ap.mixFail': 'Không trộn được: ',
'ap.errShort': 'lỗi',
+ 'vc.title': 'Giọng của tôi',
+ 'vc.optTag': 'giọng nhân bản',
+ 'vc.add': '+ Thêm giọng',
+ 'vc.loading': 'Đang tải giọng của bạn…',
+ 'vc.loadErr': 'Không tải được danh sách giọng.',
+ 'vc.retry': 'Thử lại',
+ 'vc.empty': 'Chưa có giọng nào. Tải lên hoặc thu 10 giây – 3 phút giọng nói, app học giọng rồi đọc lời video bằng chính giọng đó.',
+ 'vc.needVieneu': 'Cần VieNeu-TTS trên máy để nhân bản giọng: pip install vieneu',
+ 'vc.ready': 'Sẵn sàng',
+ 'vc.error': 'Lỗi',
+ 'vc.step.queued': 'Đang chờ…',
+ 'vc.step.transcribe': 'Đang chép lời đoạn mẫu…',
+ 'vc.step.encode': 'Đang học giọng + đọc thử…',
+ 'vc.play': 'Nghe thử giọng {name}',
+ 'vc.stop': 'Dừng nghe',
+ 'vc.rename': 'Đổi tên giọng {name}',
+ 'vc.delete': 'Xoá giọng {name}',
+ 'vc.newName': 'Tên mới',
+ 'vc.save': 'Lưu',
+ 'vc.cancel': 'Huỷ',
+ 'vc.refSum': 'Đoạn mẫu app đã chọn',
+ 'vc.refText': 'Lời của đoạn mẫu',
+ 'vc.byWhisper': '(máy tự chép, sửa nếu sai)',
+ 'vc.refTextPh': 'Gõ đúng những gì bạn nói trong đoạn mẫu',
+ 'vc.refTextHint': 'Không bắt buộc với VieNeu v3 Turbo; giúp nhận ra đoạn mẫu nói gì.',
+ 'vc.saveText': 'Lưu lời',
+ 'vc.noWhisper': 'Máy chưa có whisper nên chưa chép được lời đoạn mẫu. Mở "Đoạn mẫu" để nghe và gõ lời (không bắt buộc).',
+ 'vc.srcAria': 'Lấy giọng từ',
+ 'vc.srcFile': 'Chọn file',
+ 'vc.srcRec': 'Thu âm',
+ 'vc.fileLabel': 'File âm thanh giọng nói',
+ 'vc.fileHint': 'wav, mp3, m4a, ogg hoặc webm · 10 giây – 3 phút · tối đa {max} MB · chỉ 1 người nói, ít tạp âm.',
+ 'vc.readTip': 'Gợi ý: đọc to đoạn này, tự nhiên như đang nói chuyện',
+ 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
+ 'vc.recStart': 'Bắt đầu thu',
+ 'vc.recAgain': 'Thu lại',
+ 'vc.recStop': 'Dừng',
+ 'vc.recHint': 'Thu ở chỗ yên tĩnh, cách micro một gang tay, ít nhất 20 giây. Tự dừng sau 3 phút.',
+ 'vc.recFile': 'thu-am',
+ 'vc.nameLabel': 'Tên giọng',
+ 'vc.namePh': 'Ví dụ: Giọng Nam',
+ 'vc.consent': 'Đây là giọng của tôi, hoặc tôi được người đó cho phép dùng',
+ 'vc.langNote': 'Giọng nhân bản đọc tiếng Việt. Chọn giọng này cho nội dung tiếng Anh thì lời đọc được viết bằng tiếng Việt.',
+ 'vc.create': 'Tạo giọng',
+ 'vc.sending': 'Đang gửi… {pct}%',
+ 'vc.processing': 'Đã nhận giọng {name}. Đang học giọng, khoảng 1 phút.',
+ 'vc.readyNote': 'Giọng {name} đã sẵn sàng và được chọn làm giọng đọc. Bấm nút phát để nghe thử.',
+ 'vc.errNoFile': 'Chọn 1 file âm thanh.',
+ 'vc.errNoRec': 'Thu âm trước đã.',
+ 'vc.errExt': 'Định dạng chưa hỗ trợ. Dùng wav, mp3, m4a, ogg hoặc webm.',
+ 'vc.errBig': 'File quá lớn (tối đa {max} MB).',
+ 'vc.errShort': 'Ngắn quá ({s} giây). Cần ít nhất 10 giây.',
+ 'vc.errLong': 'Dài quá 3 phút. Cắt bớt rồi thử lại.',
+ 'vc.errName': 'Đặt tên cho giọng.',
+ 'vc.errNameLong': 'Tên tối đa {max} ký tự.',
+ 'vc.errConsent': 'Tick xác nhận để tiếp tục.',
+ 'vc.errNoMic': 'Trình duyệt này không thu âm được. Chọn file thay thế.',
+ 'vc.errMicDenied': 'Chưa được dùng micro. Cho phép micro trong trình duyệt rồi thử lại.',
+ 'vc.errUpload': 'Gửi không được. Kiểm tra app còn chạy rồi thử lại.',
+ 'vc.errDel': 'Không xoá được giọng.',
+ 'vc.errSave': 'Không lưu được.',
+ 'vc.confirmDel': 'Xoá giọng "{name}"? File giọng trên máy bị xoá hẳn, không khôi phục được.',
+ 'vc.deleted': 'Đã xoá giọng {name}.',
+ 'vc.renamed': 'Đã đổi tên thành {name}.',
+ 'vc.textSaved': 'Đã lưu lời đoạn mẫu.',
'ed.aria': 'Edit video của bạn',
'ed.setupH': 'Chưa cài phần Edit video',
@@ -462,6 +527,71 @@
'ap.loading': 'Loading…',
'ap.mixFail': "Couldn't mix: ",
'ap.errShort': 'error',
+ 'vc.title': 'My voices',
+ 'vc.optTag': 'cloned voice',
+ 'vc.add': '+ Add voice',
+ 'vc.loading': 'Loading your voices…',
+ 'vc.loadErr': "Couldn't load your voices.",
+ 'vc.retry': 'Retry',
+ 'vc.empty': 'No voices yet. Upload or record 10 seconds to 3 minutes of speech and the app learns it, then reads your video script in that voice.',
+ 'vc.needVieneu': 'Voice cloning needs VieNeu-TTS on this machine: pip install vieneu',
+ 'vc.ready': 'Ready',
+ 'vc.error': 'Error',
+ 'vc.step.queued': 'Waiting…',
+ 'vc.step.transcribe': 'Transcribing the sample…',
+ 'vc.step.encode': 'Learning the voice + test read…',
+ 'vc.play': 'Play sample of {name}',
+ 'vc.stop': 'Stop',
+ 'vc.rename': 'Rename voice {name}',
+ 'vc.delete': 'Delete voice {name}',
+ 'vc.newName': 'New name',
+ 'vc.save': 'Save',
+ 'vc.cancel': 'Cancel',
+ 'vc.refSum': 'Sample the app picked',
+ 'vc.refText': 'Words spoken in the sample',
+ 'vc.byWhisper': '(auto-transcribed, fix if wrong)',
+ 'vc.refTextPh': 'Type exactly what you say in the sample',
+ 'vc.refTextHint': 'Optional for VieNeu v3 Turbo; helps you see what the sample says.',
+ 'vc.saveText': 'Save text',
+ 'vc.noWhisper': "Whisper isn't installed, so the sample wasn't transcribed. Open the sample to listen and type it (optional).",
+ 'vc.srcAria': 'Voice source',
+ 'vc.srcFile': 'Choose file',
+ 'vc.srcRec': 'Record',
+ 'vc.fileLabel': 'Voice audio file',
+ 'vc.fileHint': 'wav, mp3, m4a, ogg or webm · 10 seconds to 3 minutes · up to {max} MB · one speaker, little background noise.',
+ 'vc.readTip': 'Tip: read this aloud naturally (Vietnamese text, since cloned voices speak Vietnamese)',
+ 'vc.readText': 'Hôm nay mình muốn kể cho bạn nghe một chuyện nhỏ. Sáng nào mình cũng dậy sớm, pha một ly cà phê, mở cửa sổ và nghe phố xá bắt đầu nhộn nhịp. Có hôm trời mưa, có hôm nắng gắt, nhưng mình vẫn giữ thói quen đó. Một, hai, ba, bốn, năm: thói quen nhỏ, kết quả lớn.',
+ 'vc.recStart': 'Start recording',
+ 'vc.recAgain': 'Record again',
+ 'vc.recStop': 'Stop',
+ 'vc.recHint': 'Record somewhere quiet, a hand-width from the mic, at least 20 seconds. Stops by itself at 3 minutes.',
+ 'vc.recFile': 'recording',
+ 'vc.nameLabel': 'Voice name',
+ 'vc.namePh': 'e.g. My voice',
+ 'vc.consent': "This is my voice, or I have that person's permission to use it",
+ 'vc.langNote': 'Cloned voices speak Vietnamese. Pick one for English content and the voiceover is written in Vietnamese.',
+ 'vc.create': 'Create voice',
+ 'vc.sending': 'Uploading… {pct}%',
+ 'vc.processing': 'Got voice {name}. Learning it now, about a minute.',
+ 'vc.readyNote': 'Voice {name} is ready and selected as the voiceover. Press play to hear it.',
+ 'vc.errNoFile': 'Choose an audio file.',
+ 'vc.errNoRec': 'Record something first.',
+ 'vc.errExt': 'Unsupported format. Use wav, mp3, m4a, ogg or webm.',
+ 'vc.errBig': 'File too large (max {max} MB).',
+ 'vc.errShort': 'Too short ({s} seconds). It needs at least 10 seconds.',
+ 'vc.errLong': 'Longer than 3 minutes. Trim it and try again.',
+ 'vc.errName': 'Give the voice a name.',
+ 'vc.errNameLong': 'Name can be up to {max} characters.',
+ 'vc.errConsent': 'Tick the confirmation to continue.',
+ 'vc.errNoMic': "This browser can't record. Choose a file instead.",
+ 'vc.errMicDenied': 'Microphone access was blocked. Allow it in the browser and try again.',
+ 'vc.errUpload': 'Upload failed. Check the app is still running and try again.',
+ 'vc.errDel': "Couldn't delete the voice.",
+ 'vc.errSave': "Couldn't save.",
+ 'vc.confirmDel': 'Delete voice "{name}"? Its files on this machine are removed for good.',
+ 'vc.deleted': 'Deleted voice {name}.',
+ 'vc.renamed': 'Renamed to {name}.',
+ 'vc.textSaved': 'Sample text saved.',
'ed.aria': 'Edit your video',
'ed.setupH': "Video editing isn't installed",
diff --git a/server/public/index.html b/server/public/index.html
index 4e0e0af..20dfece 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -202,6 +202,7 @@
<script src="/i18n.js"></script>
<script src="/audio-panel.js"></script>
+<script src="/voice-clone.js"></script>
<script src="/app.js"></script>
<script src="/edit-panel.js"></script>
</body>
diff --git a/server/public/voice-clone.css b/server/public/voice-clone.css
new file mode 100644
index 0000000..2438ed1
--- /dev/null
+++ b/server/public/voice-clone.css
@@ -0,0 +1,61 @@
+/* "Giọng của tôi" (voice-clone.js). Dùng token màu của style.css. */
+.vc { margin-top: 12px; padding: 12px; border: 1px dashed var(--line); border-radius: 12px; background: var(--panel-2); }
+.vc-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.vc-head h3 { margin: 0; font-size: 15px; font-weight: 700; color: var(--ink); }
+.vc-btn { min-height: 44px; padding: 0 14px; display: inline-flex; align-items: center; gap: 6px; border-radius: 10px; border: 1px solid var(--line); background: var(--panel); color: var(--ink); font-weight: 600; cursor: pointer; transition: background .15s, transform .1s; }
+.vc-btn:hover { background: var(--line); }
+.vc-btn:active { transform: scale(.97); }
+.vc-btn.pri { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
+.vc-btn:disabled { opacity: .5; cursor: not-allowed; }
+.vc-btn svg { width: 18px; height: 18px; fill: currentColor; }
+.vc-empty { margin-top: 8px; font-size: 14px; color: var(--ink-2); line-height: 1.5; }
+.vc-dim { color: var(--ink-3); font-size: 13px; }
+
+.vc-list { list-style: none; margin: 8px 0 0; padding: 0; }
+.vc-item { padding: 8px 0; border-top: 1px solid var(--line); }
+.vc-item:first-child { border-top: 0; }
+.vc-row { display: flex; align-items: center; gap: 8px; }
+.vc-ph { flex: none; width: 44px; height: 44px; }
+.vc-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
+.vc-name { font-weight: 600; overflow-wrap: anywhere; }
+.vc-chip { align-self: flex-start; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; padding: 2px 8px; border-radius: 999px; background: var(--panel); color: var(--ink-2); }
+.vc-chip.ok { color: var(--ok); }
+.vc-chip.bad { color: var(--bad); }
+.vc-chip .ap-spin { width: 12px; height: 12px; }
+.vc-icon { flex: none; width: 44px; height: 44px; display: grid; place-items: center; border-radius: 10px; border: 1px solid transparent; background: none; color: var(--ink-2); cursor: pointer; }
+.vc-icon:hover { background: var(--line); color: var(--ink); }
+.vc-icon:disabled { opacity: .4; cursor: not-allowed; }
+.vc-icon svg { width: 20px; height: 20px; }
+.vc-ren { flex: 1; display: flex; flex-wrap: wrap; gap: 8px; }
+.vc-ren input { flex: 1 1 140px; min-width: 0; min-height: 44px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; }
+.vc-ref { margin-top: 6px; }
+.vc-ref > summary { min-height: 36px; display: flex; align-items: center; cursor: pointer; color: var(--ink-2); font-size: 14px; }
+.vc-ref audio, .vc-picked audio { width: 100%; height: 40px; margin-top: 6px; }
+.vc-reftext textarea { min-height: 64px; }
+.vc-reftext .vc-btn { margin-top: 8px; }
+
+.vc-form { margin-top: 8px; }
+.vc-seg { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; padding: 4px; border-radius: 12px; background: var(--bg); border: 1px solid var(--line); }
+.vc-seg button { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 0; border-radius: 9px; background: none; color: var(--ink-2); font-weight: 600; cursor: pointer; }
+.vc-seg button svg { width: 18px; height: 18px; }
+.vc-seg button[aria-pressed="true"] { background: var(--panel-2); color: var(--ink); box-shadow: 0 1px 0 var(--line); }
+.vc-file { display: block; width: 100%; min-height: 44px; padding: 8px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg); }
+.vc-form input#vcName { display: block; width: 100%; min-height: 44px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 0 12px; }
+.vc-form [aria-invalid="true"] { border-color: var(--bad); }
+.vc-read { margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--bg); border: 1px solid var(--line); }
+.vc-read p { margin: 6px 0 0; line-height: 1.6; color: var(--ink); }
+.vc-recgo { margin-top: 12px; width: 100%; justify-content: center; }
+.vc-rec { margin-top: 12px; display: flex; align-items: center; gap: 12px; }
+.vc-rec .vc-btn { margin-left: auto; }
+.vc-dot { width: 12px; height: 12px; border-radius: 50%; background: var(--bad); animation: vc-blink 1s ease-in-out infinite; }
+@keyframes vc-blink { 50% { opacity: .3; } }
+@media (prefers-reduced-motion: reduce) { .vc-dot { animation: none; } }
+.vc-timer { font: 600 18px/1 var(--mono); font-variant-numeric: tabular-nums; }
+.vc-picked { margin-top: 12px; font-size: 14px; color: var(--ink-2); overflow-wrap: anywhere; }
+.vc-consent { display: flex; align-items: flex-start; gap: 10px; margin-top: 12px; min-height: 44px; cursor: pointer; line-height: 1.45; }
+.vc-consent input { flex: none; width: 22px; height: 22px; margin-top: 1px; accent-color: var(--accent); }
+.vc-err { margin-top: 6px; font-size: 14px; color: var(--bad); }
+.vc-actions { display: flex; gap: 8px; align-items: stretch; margin-top: 4px; }
+.vc-actions .ap-go { flex: 1; }
+.vc-actions .vc-btn { margin-top: 12px; }
+.vc-live:empty { display: none; }
diff --git a/server/public/voice-clone.js b/server/public/voice-clone.js
new file mode 100644
index 0000000..7c4820d
--- /dev/null
+++ b/server/public/voice-clone.js
@@ -0,0 +1,316 @@
+// "Giọng của tôi": nhân bản giọng người dùng (tải file hoặc thu âm bằng micro) → dùng như giọng có sẵn.
+// Tự chứa: tự nạp CSS, tạo 1 khối (window.LumVoices.el) mà audio-panel.js gắn ngay dưới ô "Giọng đọc".
+// API: GET/POST /api/voices/mine · PATCH/DELETE /api/voices/mine/:id · /api/voices/mine/:id/(sample|ref).wav
+(() => {
+ const $ = (s, el = document) => el.querySelector(s);
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ const t = (k, v) => window.I18N.t(k, v);
+ const css = document.createElement('link');
+ css.rel = 'stylesheet'; css.href = '/voice-clone.css';
+ document.head.appendChild(css);
+
+ const IC = {
+ play: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>',
+ stop: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>',
+ edit: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4L19 9l-4-4L4 16v4z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>',
+ del: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ mic: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3" fill="none" stroke="currentColor" stroke-width="2"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
+ file: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H6v18h12V7z M14 3v4h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>',
+ };
+ const fmtT = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
+
+ let data = { voices: [], support: { vieneu: true, whisper: true }, limits: { minS: 10, maxS: 180, maxBytes: 30 * 1024 * 1024, nameMax: 40, ext: ['.wav', '.mp3', '.m4a', '.ogg', '.webm'] } };
+ let loadState = 'loading'; // loading | ok | error
+ let formOpen = false;
+ let editing = null; // id đang đổi tên
+ let pollTimer = null;
+ // trạng thái form (giữ khi vẽ lại do đổi ngôn ngữ)
+ const F = { mode: 'file', blob: null, blobName: '', blobUrl: '', durS: null, name: '', consent: false, err: {}, sending: false, pct: 0 };
+ let rec = null; // { mr, stream, t0, timer, chunks }
+
+ const el = document.createElement('section');
+ el.className = 'vc';
+ el.setAttribute('aria-labelledby', 'vcTitle');
+
+ // ---------- trình phát chung ----------
+ const player = new Audio();
+ let playing = null;
+ player.addEventListener('ended', () => setPlaying(null));
+ function setPlaying(btn) {
+ if (playing && playing !== btn) { playing.innerHTML = IC.play; playing.setAttribute('aria-label', t('vc.play', { name: playing.dataset.name })); }
+ playing = btn;
+ if (btn) { btn.innerHTML = IC.stop; btn.setAttribute('aria-label', t('vc.stop')); }
+ }
+ function togglePlay(btn, url) {
+ if (playing === btn) { player.pause(); setPlaying(null); btn.innerHTML = IC.play; btn.setAttribute('aria-label', t('vc.play', { name: btn.dataset.name })); return; }
+ player.src = url + '?v=' + Date.now();
+ player.play().then(() => setPlaying(btn)).catch(() => setPlaying(null));
+ }
+
+ // ---------- dữ liệu ----------
+ async function load() {
+ try {
+ const r = await fetch('/api/voices/mine');
+ if (!r.ok) throw new Error();
+ data = await r.json();
+ loadState = 'ok';
+ } catch { loadState = 'error'; }
+ render();
+ schedulePoll();
+ }
+ function schedulePoll() {
+ clearTimeout(pollTimer);
+ if (data.voices.some((v) => v.status === 'processing')) pollTimer = setTimeout(async () => {
+ const before = new Map(data.voices.map((v) => [v.id, v.status]));
+ await load();
+ // vừa xong → chọn luôn giọng này trong ô "Giọng đọc"
+ const fresh = data.voices.find((v) => before.get(v.id) === 'processing' && v.status === 'ready');
+ if (fresh) { window.LumAudio?.reload(fresh.id); announce(t('vc.readyNote', { name: fresh.name })); }
+ else if (data.voices.some((v) => before.get(v.id) === 'processing' && v.status !== 'processing')) window.LumAudio?.reload();
+ }, 2500);
+ }
+ // vùng đọc thông báo cho trình đọc màn hình + hiện chữ ngắn: giữ nguyên qua các lần vẽ lại
+ const live = document.createElement('div');
+ live.className = 'vc-live hint'; live.setAttribute('role', 'status'); live.setAttribute('aria-live', 'polite');
+ const announce = (msg) => { live.textContent = msg; };
+
+ // ---------- vẽ ----------
+ function statusChip(v) {
+ if (v.status === 'ready') return `<span class="vc-chip ok">${esc(t('vc.ready'))}</span>`;
+ if (v.status === 'error') return `<span class="vc-chip bad">${esc(t('vc.error'))}</span>`;
+ return `<span class="vc-chip busy"><span class="ap-spin" aria-hidden="true"></span>${esc(t('vc.step.' + (v.step || 'queued')))}</span>`;
+ }
+ function itemHtml(v) {
+ const ren = editing === v.id;
+ const name = ren
+ ? `<form class="vc-ren" data-ren="${esc(v.id)}"><label class="sr" for="vcRen${esc(v.id)}">${esc(t('vc.newName'))}</label>
+ <input id="vcRen${esc(v.id)}" maxlength="${data.limits.nameMax}" value="${esc(v.name)}" required />
+ <button type="submit" class="vc-btn pri">${esc(t('vc.save'))}</button><button type="button" class="vc-btn" data-act="cancel">${esc(t('vc.cancel'))}</button></form>`
+ : `<div class="vc-name">${esc(v.name)}</div>`;
+ const refBox = v.refAudio ? `<details class="vc-ref"><summary>${esc(t('vc.refSum'))}${v.ref ? ` · ${v.ref.durS.toLocaleString(window.I18N.locale)} s` : ''}</summary>
+ <audio controls preload="none" src="${esc(v.refAudio)}"></audio>
+ <form class="vc-reftext" data-reftext="${esc(v.id)}">
+ <label class="field" for="vcRt${esc(v.id)}">${esc(t('vc.refText'))}${v.refTextSource === 'whisper' ? ` <span class="vc-dim">${esc(t('vc.byWhisper'))}</span>` : ''}</label>
+ <textarea id="vcRt${esc(v.id)}" rows="2" maxlength="600" placeholder="${esc(t('vc.refTextPh'))}">${esc(v.refText || '')}</textarea>
+ <div class="hint">${esc(t('vc.refTextHint'))}</div>
+ <button type="submit" class="vc-btn">${esc(t('vc.saveText'))}</button>
+ </form></details>` : '';
+ return `<li class="vc-item" data-id="${esc(v.id)}">
+ <div class="vc-row">
+ ${v.sample ? `<button type="button" class="ap-play" data-act="play" data-url="${esc(v.sample)}" data-name="${esc(v.name)}" aria-label="${esc(t('vc.play', { name: v.name }))}">${IC.play}</button>` : '<span class="vc-ph" aria-hidden="true"></span>'}
+ <div class="vc-main">${name}${ren ? '' : statusChip(v)}</div>
+ ${ren ? '' : `<button type="button" class="vc-icon" data-act="rename" aria-label="${esc(t('vc.rename', { name: v.name }))}">${IC.edit}</button>
+ <button type="button" class="vc-icon" data-act="delete" aria-label="${esc(t('vc.delete', { name: v.name }))}" ${v.status === 'processing' ? 'disabled' : ''}>${IC.del}</button>`}
+ </div>
+ ${v.status === 'error' && v.error ? `<div class="errmsg">${esc(v.error)}</div>` : ''}
+ ${v.status === 'ready' && !v.refText && !data.support.whisper ? `<div class="hint">${esc(t('vc.noWhisper'))}</div>` : ''}
+ ${refBox}
+ </li>`;
+ }
+ function formHtml() {
+ const L = data.limits;
+ const e = (k) => (F.err[k] ? `<div class="vc-err" id="vcErr-${k}">${esc(F.err[k])}</div>` : '');
+ const desc = (k) => (F.err[k] ? `aria-describedby="vcErr-${k}" aria-invalid="true"` : '');
+ const recUI = rec
+ ? `<div class="vc-rec on"><span class="vc-dot" aria-hidden="true"></span><span class="vc-timer" role="timer" aria-live="off">${fmtT((Date.now() - rec.t0) / 1000)} / ${fmtT(L.maxS)}</span>
+ <button type="button" class="vc-btn pri" data-act="recstop">${IC.stop}<span>${esc(t('vc.recStop'))}</span></button></div>`
+ : `<button type="button" class="vc-btn pri vc-recgo" data-act="recstart">${IC.mic}<span>${esc(F.blob && F.mode === 'rec' ? t('vc.recAgain') : t('vc.recStart'))}</span></button>`;
+ return `<form class="vc-form" novalidate>
+ <div class="vc-seg" role="group" aria-label="${esc(t('vc.srcAria'))}">
+ <button type="button" data-mode="file" aria-pressed="${F.mode === 'file'}">${IC.file}<span>${esc(t('vc.srcFile'))}</span></button>
+ <button type="button" data-mode="rec" aria-pressed="${F.mode === 'rec'}">${IC.mic}<span>${esc(t('vc.srcRec'))}</span></button>
+ </div>
+ ${F.mode === 'file' ? `
+ <label class="field" for="vcFile">${esc(t('vc.fileLabel'))}</label>
+ <input id="vcFile" class="vc-file" type="file" accept="audio/*,${L.ext.join(',')}" ${desc('file')} />
+ <div class="hint">${esc(t('vc.fileHint', { max: Math.round(L.maxBytes / 1024 / 1024) }))}</div>`
+ : `
+ <div class="vc-read"><div class="vc-dim">${esc(t('vc.readTip'))}</div><p lang="vi">${esc(t('vc.readText'))}</p></div>
+ ${recUI}
+ <div class="hint">${esc(t('vc.recHint'))}</div>`}
+ ${F.blob ? `<div class="vc-picked"><span>${esc(F.blobName)}${F.durS ? ` · ${fmtT(F.durS)}` : ''}</span><audio controls src="${esc(F.blobUrl)}"></audio></div>` : ''}
+ ${e('file')}
+ <label class="field" for="vcName">${esc(t('vc.nameLabel'))}</label>
+ <input id="vcName" maxlength="${L.nameMax}" autocomplete="off" placeholder="${esc(t('vc.namePh'))}" value="${esc(F.name)}" ${desc('name')} />
+ ${e('name')}
+ <label class="vc-consent"><input type="checkbox" id="vcConsent" ${F.consent ? 'checked' : ''} ${desc('consent')} /><span>${esc(t('vc.consent'))}</span></label>
+ ${e('consent')}
+ <div class="hint">${esc(t('vc.langNote'))}</div>
+ ${e('form')}
+ <div class="vc-actions">
+ <button type="submit" class="ap-go" ${F.sending || rec ? 'disabled' : ''}>${F.sending ? esc(t('vc.sending', { pct: F.pct })) : esc(t('vc.create'))}</button>
+ <button type="button" class="vc-btn" data-act="close">${esc(t('vc.cancel'))}</button>
+ </div>
+ </form>`;
+ }
+ function render() {
+ const canAdd = data.support.vieneu;
+ const list = loadState === 'loading' ? `<div class="hint">${esc(t('vc.loading'))}</div>`
+ : loadState === 'error' ? `<div class="errmsg">${esc(t('vc.loadErr'))} <button type="button" class="vc-btn" data-act="retry">${esc(t('vc.retry'))}</button></div>`
+ : data.voices.length ? `<ul class="vc-list">${data.voices.map(itemHtml).join('')}</ul>`
+ : formOpen ? '' : `<div class="vc-empty">${esc(t('vc.empty'))}</div>`;
+ el.innerHTML = `<div class="vc-head"><h3 id="vcTitle">${esc(t('vc.title'))}</h3>
+ ${formOpen ? '' : `<button type="button" class="vc-btn pri" data-act="open" ${canAdd ? '' : 'disabled'}>${esc(t('vc.add'))}</button>`}</div>
+ ${canAdd ? '' : `<div class="hint ap-hint">${esc(t('vc.needVieneu'))}</div>`}
+ ${list}
+ ${formOpen ? formHtml() : ''}`;
+ el.appendChild(live);
+ }
+
+ // ---------- kiểm phía máy (báo lỗi bằng ngôn ngữ giao diện) ----------
+ function probeDuration(url) {
+ return new Promise((res) => {
+ const a = new Audio(); a.preload = 'metadata';
+ a.onloadedmetadata = () => res(Number.isFinite(a.duration) ? a.duration : null);
+ a.onerror = () => res(null);
+ a.src = url;
+ setTimeout(() => res(null), 4000);
+ });
+ }
+ async function setBlob(blob, name) {
+ if (F.blobUrl) URL.revokeObjectURL(F.blobUrl);
+ F.blob = blob; F.blobName = name; F.blobUrl = URL.createObjectURL(blob); F.durS = await probeDuration(F.blobUrl);
+ F.err.file = checkFile();
+ if (!F.err.file) delete F.err.file;
+ }
+ function checkFile() {
+ const L = data.limits;
+ if (!F.blob) return t(F.mode === 'rec' ? 'vc.errNoRec' : 'vc.errNoFile');
+ const ext = (F.blobName.match(/\.[a-z0-9]+$/i) || [''])[0].toLowerCase();
+ if (!L.ext.includes(ext)) return t('vc.errExt');
+ if (F.blob.size > L.maxBytes) return t('vc.errBig', { max: Math.round(L.maxBytes / 1024 / 1024) });
+ if (F.durS != null && F.durS < L.minS) return t('vc.errShort', { s: F.durS.toLocaleString(window.I18N.locale, { maximumFractionDigits: 1 }) });
+ if (F.durS != null && F.durS > L.maxS + 0.5) return t('vc.errLong');
+ return null;
+ }
+ function validate() {
+ F.err = {};
+ const fe = checkFile(); if (fe) F.err.file = fe;
+ const n = F.name.trim();
+ if (!n) F.err.name = t('vc.errName');
+ else if ([...n].length > data.limits.nameMax) F.err.name = t('vc.errNameLong', { max: data.limits.nameMax });
+ if (!F.consent) F.err.consent = t('vc.errConsent');
+ return !Object.keys(F.err).length;
+ }
+
+ // ---------- thu âm ----------
+ function pickMime() {
+ const c = [['audio/webm;codecs=opus', '.webm'], ['audio/webm', '.webm'], ['audio/ogg;codecs=opus', '.ogg'], ['audio/mp4', '.m4a']];
+ return c.find(([m]) => window.MediaRecorder?.isTypeSupported?.(m)) || ['', '.webm'];
+ }
+ async function recStart() {
+ delete F.err.file;
+ if (!navigator.mediaDevices?.getUserMedia || !window.MediaRecorder) { F.err.file = t('vc.errNoMic'); render(); return; }
+ let stream;
+ try { stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, channelCount: 1 } }); }
+ catch { F.err.file = t('vc.errMicDenied'); render(); return; }
+ const [mime, ext] = pickMime();
+ const mr = new MediaRecorder(stream, mime ? { mimeType: mime } : undefined);
+ const chunks = [];
+ mr.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
+ mr.onstop = async () => {
+ stream.getTracks().forEach((tr) => tr.stop());
+ const dur = (Date.now() - rec.t0) / 1000;
+ clearInterval(rec.timer); rec = null;
+ const blob = new Blob(chunks, { type: mr.mimeType || mime || 'audio/webm' });
+ await setBlob(blob, `${t('vc.recFile')}${ext}`);
+ if (F.durS == null) F.durS = dur; // webm thu từ trình duyệt thường không ghi độ dài
+ F.err.file = checkFile(); if (!F.err.file) delete F.err.file;
+ render(); $('.vc-picked audio', el)?.focus();
+ };
+ rec = { mr, stream, chunks, t0: Date.now(), timer: setInterval(() => {
+ const s = (Date.now() - rec.t0) / 1000;
+ const n = $('.vc-timer', el); if (n) n.textContent = `${fmtT(s)} / ${fmtT(data.limits.maxS)}`;
+ if (s >= data.limits.maxS) mr.stop();
+ }, 250) };
+ mr.start(1000);
+ render(); $('[data-act="recstop"]', el)?.focus();
+ }
+
+ // ---------- gửi ----------
+ function submit() {
+ if (!validate()) { render(); const first = $('[aria-invalid="true"]', el); first?.focus(); return; }
+ F.sending = true; F.pct = 0; render();
+ const fd = new FormData();
+ fd.append('name', F.name.trim());
+ fd.append('consent', '1');
+ fd.append('audio', F.blob, F.blobName);
+ const x = new XMLHttpRequest();
+ x.open('POST', '/api/voices/mine');
+ x.upload.onprogress = (e) => { if (e.lengthComputable) { F.pct = Math.round((e.loaded / e.total) * 100); const b = $('.vc-form .ap-go', el); if (b) b.textContent = t('vc.sending', { pct: F.pct }); } };
+ x.onload = () => {
+ F.sending = false;
+ let j = {}; try { j = JSON.parse(x.responseText); } catch { /* bỏ qua */ }
+ if (x.status === 202 || x.status === 200) {
+ resetForm(); formOpen = false;
+ announce(t('vc.processing', { name: j.name || '' }));
+ load();
+ } else { F.err = { form: window.I18N.srv(j.error) || t('vc.errUpload') }; render(); }
+ };
+ x.onerror = () => { F.sending = false; F.err = { form: t('vc.errUpload') }; render(); };
+ x.send(fd);
+ }
+ function resetForm() {
+ if (F.blobUrl) URL.revokeObjectURL(F.blobUrl);
+ Object.assign(F, { blob: null, blobName: '', blobUrl: '', durS: null, name: '', consent: false, err: {}, sending: false, pct: 0 });
+ }
+
+ // ---------- sự kiện ----------
+ el.addEventListener('click', async (e) => {
+ const b = e.target.closest('button'); if (!b || b.disabled) return;
+ const act = b.dataset.act, item = b.closest('.vc-item'), id = item?.dataset.id;
+ if (b.dataset.mode) { if (rec) return; F.mode = b.dataset.mode; if (F.blob) resetForm(); render(); $(`[data-mode="${F.mode}"]`, el)?.focus(); return; }
+ if (act === 'open') { formOpen = true; render(); $('[data-mode="file"]', el)?.focus(); }
+ else if (act === 'close') { if (rec) rec.mr.stop(); resetForm(); formOpen = false; render(); $('[data-act="open"]', el)?.focus(); }
+ else if (act === 'retry') { loadState = 'loading'; render(); load(); }
+ else if (act === 'recstart') recStart();
+ else if (act === 'recstop') rec?.mr.stop();
+ else if (act === 'play') togglePlay(b, b.dataset.url);
+ else if (act === 'rename') { editing = id; render(); const i = $(`#vcRen${id}`, el); i?.focus(); i?.select(); }
+ else if (act === 'cancel') { editing = null; render(); }
+ else if (act === 'delete') {
+ const v = data.voices.find((x) => x.id === id);
+ if (!window.confirm(t('vc.confirmDel', { name: v?.name || id }))) return;
+ const r = await fetch('/api/voices/mine/' + encodeURIComponent(id), { method: 'DELETE' });
+ if (!r.ok) { announce((await r.json().catch(() => ({}))).error || t('vc.errDel')); return; }
+ announce(t('vc.deleted', { name: v?.name || id }));
+ await load(); window.LumAudio?.reload();
+ }
+ });
+ el.addEventListener('change', async (e) => {
+ if (e.target.id === 'vcFile') {
+ const f = e.target.files[0];
+ if (f) { await setBlob(f, f.name); render(); }
+ } else if (e.target.id === 'vcConsent') { F.consent = e.target.checked; if (F.consent) { delete F.err.consent; render(); $('#vcConsent', el)?.focus(); } }
+ });
+ el.addEventListener('input', (e) => { if (e.target.id === 'vcName') F.name = e.target.value; });
+ el.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const f = e.target;
+ if (f.classList.contains('vc-form')) return submit();
+ const patch = async (id, body) => {
+ const r = await fetch('/api/voices/mine/' + encodeURIComponent(id), { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error || t('vc.errSave'));
+ return j;
+ };
+ try {
+ if (f.dataset.ren) {
+ const v = $('input', f).value.trim();
+ if (!v) { $('input', f).focus(); return; }
+ await patch(f.dataset.ren, { name: v });
+ editing = null; await load(); window.LumAudio?.reload(); announce(t('vc.renamed', { name: v }));
+ } else if (f.dataset.reftext) {
+ await patch(f.dataset.reftext, { refText: $('textarea', f).value });
+ announce(t('vc.textSaved')); await load();
+ }
+ } catch (err) { announce(err.message); }
+ });
+ el.addEventListener('keydown', (e) => { if (e.key === 'Escape' && editing) { editing = null; render(); } });
+
+ window.addEventListener('lumreels:lang', () => { live.textContent = ''; render(); window.LumAudio?.attachVoices(); });
+ window.LumVoices = { el, reload: load };
+ render();
+ window.LumAudio?.attachVoices();
+ load();
+})();
diff --git a/server/server.mjs b/server/server.mjs
index 7ea9b36..c6b5cfc 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -16,6 +16,8 @@ import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '.
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { synthVoice } from '../engine/audio/voice.mjs';
import { handleEditRoute, initEdits } from '../edit/http.mjs';
+import { handleVoiceRoute, initVoices } from './voices-http.mjs';
+import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
@@ -31,6 +33,8 @@ async function audioPreviewFile(q) {
const { voice: v } = normalizeAudioPrefs({ voice });
const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
+ // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
+ if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
const ve = voiceEngine(v);
const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
return r.file;
@@ -203,6 +207,8 @@ const server = http.createServer(async (req, res) => {
try {
// ---- Edit video của bạn (edit/http.mjs) ----
if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
+ // ---- Giọng của tôi (server/voices-http.mjs) ----
+ if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
// ---- API ----
if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
@@ -317,6 +323,7 @@ const server = http.createServer(async (req, res) => {
markStale();
initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
+initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
diff --git a/server/voices-http.mjs b/server/voices-http.mjs
new file mode 100644
index 0000000..ccc1d2b
--- /dev/null
+++ b/server/voices-http.mjs
@@ -0,0 +1,109 @@
+// REST cho "Giọng của tôi" (giọng nhân bản). server/server.mjs gọi handleVoiceRoute trước các route khác.
+// GET /api/voices/mine → {voices[], support{vieneu, whisper}, limits}
+// POST /api/voices/mine → multipart: name, consent=1, refText?, audio=<file> (wav/mp3/m4a/ogg/webm, 10 s – 3 phút, ≤ 30 MB)
+// 202 + giọng ở trạng thái "processing"; xong thì "ready" (có sample.wav)
+// PATCH /api/voices/mine/:id → JSON {name?, refText?}
+// DELETE /api/voices/mine/:id
+// GET /api/voices/mine/:id/sample.wav (câu nghe thử) · /ref.wav (đoạn mẫu đã chọn)
+// Lệnh ghi chặn Origin lạ. Id chỉ nhận dạng vc-<8 hex> (không thành đường dẫn khác được).
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { parseMultipart, originOk, sendAndClose } from '../edit/http.mjs';
+import { VOICES_DIR, CLONE_ID_RE, NAME_MAX, readClone, listClones, cloneView, cloneDir, renameClone, setRefText, deleteClone, markStaleClones, cleanName } from '../engine/audio/voice-store.mjs';
+import { prepareClone, finishClone, activeClones, cloneSupport, CLONE_LIMITS, CLONE_EXT } from '../engine/audio/voice-clone.mjs';
+
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
+const CONSENT_OK = (v) => v === '1' || v === 'true' || v === 'on';
+let uploading = false;
+
+export function initVoices() { markStaleClones(activeClones); }
+
+/** Trả true nếu đã xử lý route. */
+export async function handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {
+ if (p !== '/api/voices/mine' && !p.startsWith('/api/voices/mine/')) return false;
+ if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }
+
+ if (p === '/api/voices/mine') {
+ if (req.method === 'GET') {
+ const sup = cloneSupport();
+ send(res, 200, { voices: listClones().map(cloneView), support: { vieneu: sup.vieneu, whisper: sup.whisper }, limits: { ...CLONE_LIMITS, nameMax: NAME_MAX, ext: [...CLONE_EXT] } });
+ return true;
+ }
+ if (req.method === 'POST') { await createFromUpload(req, res, send); return true; }
+ send(res, 405, { error: 'method' });
+ return true;
+ }
+
+ const m = /^\/api\/voices\/mine\/([^/]*)(?:\/([^/]*))?$/.exec(p);
+ if (!m || !CLONE_ID_RE.test(m[1])) { send(res, 400, { error: 'id giọng không hợp lệ' }); return true; }
+ const id = m[1];
+ if (m[2] !== undefined) {
+ if (!['sample.wav', 'ref.wav'].includes(m[2]) || !['GET', 'HEAD'].includes(req.method)) { send(res, 404, { error: 'không thấy file' }); return true; }
+ if (!readClone(id)) { send(res, 404, { error: 'không thấy giọng' }); return true; }
+ serveFile(req, res, cloneDir(id), m[2]);
+ return true;
+ }
+ try {
+ if (req.method === 'GET') {
+ const v = cloneView(readClone(id));
+ send(res, v ? 200 : 404, v || { error: 'không thấy giọng' });
+ } else if (req.method === 'PATCH') {
+ const body = await readBody(req, 8 * 1024);
+ if (!readClone(id)) throw httpErr(404, 'không thấy giọng');
+ if (body.name === undefined && body.refText === undefined) throw httpErr(400, 'cần name hoặc refText');
+ if (body.name !== undefined) renameClone(id, body.name);
+ if (body.refText !== undefined) setRefText(id, body.refText);
+ send(res, 200, cloneView(readClone(id)));
+ } else if (req.method === 'DELETE') {
+ if (activeClones.has(id)) throw httpErr(409, 'giọng đang xử lý, chờ xong rồi xoá');
+ deleteClone(id);
+ send(res, 200, { ok: true, id });
+ } else send(res, 405, { error: 'method' });
+ } catch (e) {
+ send(res, Number.isInteger(e.code) ? e.code : 400, { error: e.message });
+ }
+ return true;
+}
+
+async function createFromUpload(req, res, send) {
+ const ct = String(req.headers['content-type'] || '');
+ if (!/^multipart\/form-data/i.test(ct)) { sendAndClose(res, req, send, 415, { error: 'cần multipart/form-data (trường audio + name + consent)' }); return; }
+ const len = Number(req.headers['content-length']);
+ const maxBody = CLONE_LIMITS.maxBytes + 256 * 1024;
+ if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length (trình duyệt tự gửi)' }); return; }
+ if (len > maxBody) { sendAndClose(res, req, send, 413, { error: 'File quá lớn (tối đa 30 MB)' }); return; }
+ if (!cloneSupport().vieneu) { sendAndClose(res, req, send, 503, { error: 'Máy chưa có VieNeu-TTS (pip install vieneu) nên chưa nhân bản giọng được' }); return; }
+ if (uploading) { sendAndClose(res, req, send, 429, { error: 'Đang nhận 1 giọng khác, chờ xong rồi gửi tiếp' }); return; }
+ uploading = true;
+ const tmp = path.join(VOICES_DIR, '_upload-' + crypto.randomBytes(4).toString('hex'));
+ try {
+ fs.mkdirSync(tmp, { recursive: true });
+ const { fields, files } = await parseMultipart(req, {
+ maxBytes: maxBody,
+ tooBig: 'File quá lớn (tối đa 30 MB)',
+ fileTarget: (field, filename, early) => {
+ if (field !== 'audio') return null;
+ // trường chữ gửi trước file → kiểm luôn, khỏi nhận cả file mới báo lỗi
+ if (early.name !== undefined) cleanName(early.name);
+ if (early.consent !== undefined && !CONSENT_OK(early.consent)) throw httpErr(400, 'Cần tick xác nhận: đây là giọng của bạn, hoặc bạn được người đó cho phép dùng');
+ const ext = path.extname(filename).toLowerCase();
+ if (!CLONE_EXT.has(ext)) throw httpErr(415, `Định dạng ${ext || '?'} chưa hỗ trợ (wav, mp3, m4a, ogg, webm)`);
+ return path.join(tmp, 'upload' + ext);
+ },
+ });
+ if (!files.audio?.size) throw httpErr(400, 'Thiếu file âm thanh');
+ if (files.audio.size > CLONE_LIMITS.maxBytes) throw httpErr(413, 'File quá lớn (tối đa 30 MB)');
+ const meta = await prepareClone({ src: files.audio.path, filename: files.audio.filename, name: fields.name, consent: fields.consent, refText: fields.refText });
+ uploading = false;
+ finishClone(meta.id, { log: (l) => console.log('[voice] ' + l) }).catch((e) => console.error('[voice]', meta.id, e.message));
+ send(res, 202, cloneView(readClone(meta.id)));
+ } catch (e) {
+ uploading = false;
+ const code = Number.isInteger(e.code) ? e.code : 422;
+ if (!res.headersSent) { if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message }); }
+ } finally {
+ uploading = false;
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+ }
+}