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.

README tiếng Anh, giọng đọc tiếng Anh (Kokoro + edge-tts), giấy phép bên thứ ba, sửa trộn tiếng hay treo

Lumtekd7e5b9a1b23b
diff --git a/.gitignore b/.gitignore
index e48c44d..f0592af 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,4 @@ __pycache__/
engine/audio/samples/voices/
jobs/*/audio/
_pr/
+_plans/
diff --git a/README.md b/README.md
index 46062d7..05877a2 100644
--- a/README.md
+++ b/README.md
@@ -1,111 +1,119 @@
<p align="center">
- <a href="https://reels.lumtek.net"><img src="docs/img/readme/banner.jpg" alt="LumReels: gõ nội dung, chọn 1 mẫu phong cách, AI viết cảnh bằng code và xuất video dọc 9:16" width="100%"></a>
+ <a href="https://reels.lumtek.net"><img src="docs/img/readme/banner-en.jpg" alt="LumReels: type your content, pick a style, AI codes the scene and renders a 9:16 video" width="100%"></a>
</p>
+<p align="center"><b>English</b> · <a href="README.vi.md">Tiếng Việt</a></p>
+
<p align="center">
- <a href="https://reels.lumtek.net"><img alt="Xem các mẫu" src="https://img.shields.io/badge/xem_m%E1%BA%ABu-reels.lumtek.net-ff4f6d?style=for-the-badge"></a>
+ <a href="https://reels.lumtek.net"><img alt="Browse the styles" src="https://img.shields.io/badge/browse_styles-reels.lumtek.net-ff4f6d?style=for-the-badge"></a>
<a href="LICENSE"><img alt="MIT" src="https://img.shields.io/badge/license-MIT-a46bff?style=for-the-badge"></a>
<img alt="Node 22+" src="https://img.shields.io/badge/node-22%2B-3c873a?style=for-the-badge&logo=node.js&logoColor=white">
- <img alt="MCP" src="https://img.shields.io/badge/MCP-s%E1%BA%B5n_s%C3%A0ng-111?style=for-the-badge">
+ <img alt="MCP ready" src="https://img.shields.io/badge/MCP-ready-111?style=for-the-badge">
</p>
<p align="center">
- <b>LumReels</b> biến một đoạn chữ thành video dọc 1080×1920 theo một trong hơn 100 mẫu phong cách (mỗi tuần thêm mẫu mới).<br>
- Không cắt ghép footage, không kho template kéo thả: AI đọc bản mô tả phong cách rồi <b>viết một cảnh HTML/SVG/WebGL mới</b>, máy render ra MP4 có nhạc, tiếng động và giọng đọc tiếng Việt.
+ <b>LumReels</b> turns a piece of text into a 1080×1920 vertical video in one of 100+ visual styles, with new styles added every week.<br>
+ No stock footage and no drag-and-drop templates. The AI reads a written description of the style and <b>codes a brand-new HTML/SVG/WebGL scene</b> for your content. Then it renders an MP4 with music, sound effects and an English or Vietnamese voice-over.
</p>
<p align="center">
- <img src="docs/img/readme/demo.webp" alt="6 video dựng bằng LumReels: hố đen, mười chất liệu, poster risograph, sa mạc xà cừ, game PS1, vệt sáng phơi sáng" width="100%">
- <br><sub>Hố đen giả định · Mười chất liệu · Poster risograph · Sa mạc xà cừ · Game 3D PS1 · Vệt sáng phơi sáng</sub>
+ <img src="docs/img/readme/demo.webp" alt="Six videos made with LumReels: black hole, ten materials, risograph poster, nacre desert, PS1 low-poly game, long-exposure light trails" width="100%">
+ <br><sub>Black hole · Ten materials · Risograph poster · Nacre desert · PS1 low-poly game · Long-exposure light trails</sub>
</p>
---
-## Làm được gì
+## What it does
| | |
|---|---|
-| 🎬 **Hơn 100 mẫu phong cách** | Faceless, quảng cáo, đa phong cách: shader vũ trụ, 3D low-poly, giấy cắt, pixel 8-bit, risograph, terminal… Mỗi mẫu là một file mô tả bằng chữ (màu, font, bố cục, nhịp theo giây), không kèm video gốc. |
-| ✍️ **AI viết cảnh, không ghép template** | Claude viết cảnh mới cho từng nội dung, tự xem ảnh xem thử và sửa. Nút **Viết lại kịch bản** xếp chữ của mày vào đúng ô của mẫu. |
-| 🔊 **Âm thanh trọn gói** | 6 kiểu nhạc nền, ~30 tiếng động gắn theo chuyển động, giọng Việt (VieNeu chạy trên máy, dự phòng edge-tts), chuẩn −14 LUFS. Đổi nhạc/giọng không phải dựng lại hình. |
-| 🤖 **Cho AI agent gọi thẳng** | MCP server, CLI và REST. Claude, Codex hay agent bất kỳ: tạo video, gửi cảnh, xem thử, render, hẹn giờ, chép MP4 ra Google Drive. |
-| ⏱️ **3 giây tới 10 phút** | Gõ `90` hoặc `1:30`. Video dài tự chia cảnh, mỗi khung là hàm thuần theo thời gian nên render ổn định. |
-| 🇻🇳 **Tiếng Việt chuẩn** | 25 họ font có dấu tiếng Việt, tự kiểm font thiếu dấu, chữ tràn khung, chữ quá nhỏ trước khi render. |
+| 🎬 **100+ styles** | Faceless explainers, ads and mixed-media: cosmic shaders, low-poly 3D, paper cut-outs, 8-bit pixel art, risograph, terminal UIs… Each style is a text file (palette, fonts, layout, beat-by-beat timing), not a video. |
+| ✍️ **AI writes the scene** | Claude writes a fresh scene for every piece of content, then checks its own preview frames and fixes what it sees. A **Rewrite script** button fits your text into the style's slots. |
+| 🔊 **Sound included** | 6 music styles and ~30 sound effects, all synthesized and synced to the motion. English voices come from Kokoro and Vietnamese voices from VieNeu, both running locally with edge-tts as fallback. Mixed to −14 LUFS. Swap music or voice without re-rendering the picture. |
+| 🤖 **Built for AI agents** | MCP server, CLI and REST. Claude, Codex or any agent can create a video, submit a scene, preview, render, schedule, and drop the MP4 into a Google Drive folder. |
+| ⏱️ **3 seconds to 10 minutes** | Type `90` or `1:30`. Long videos are split into scenes, and every frame is a pure function of time, so renders are deterministic. |
+| 🔤 **Typography that holds up** | 25 font families with full Vietnamese diacritics. Missing glyphs, overflowing text and tiny type are flagged before rendering. |
-## Thư viện mẫu
+## Style library
<p align="center">
- <a href="https://reels.lumtek.net"><img src="docs/img/readme/mau.jpg" alt="Lưới mẫu phong cách của LumReels" width="100%"></a>
- <br><sub>Mẫu nào cũng đã dựng thử bằng chính LumReels. Bấm để xem video có tiếng trên <a href="https://reels.lumtek.net">reels.lumtek.net</a>.</sub>
+ <a href="https://reels.lumtek.net"><img src="docs/img/readme/mau.jpg" alt="Grid of LumReels styles" width="100%"></a>
+ <br><sub>Every style has been test-rendered with LumReels itself. Click to watch them with sound on <a href="https://reels.lumtek.net">reels.lumtek.net</a>.</sub>
</p>
-## Chạy thử trong 2 phút
+## Quick start
-Cần **Node 22+**, **ffmpeg** và **Google Chrome**.
+You need **Node 22+**, **ffmpeg** and **Google Chrome**.
```bash
git clone https://github.com/lumtekvn/lumreels.git
cd lumreels
-npm install # tự chép three/gsap và 25 họ font tiếng Việt
-npm start # mở http://127.0.0.1:4400
+npm install # copies three/gsap and 25 font families
+npm start # opens http://127.0.0.1:4400
```
-Chọn mẫu → gõ nội dung → chọn thời lượng, nhạc, giọng → **Tạo video**.
+Pick a style, type your content, choose length, music and voice, then hit **Create video**. The web UI is in Vietnamese for now; the API, CLI and MCP tools work with content in any language.
+
+<p align="center"><img src="docs/img/ui-luoi-mau.png" alt="LumReels UI: style grid on the left; content, length and audio on the right" width="88%"></p>
-<p align="center"><img src="docs/img/ui-luoi-mau.png" alt="Giao diện LumReels: lưới mẫu bên trái, nội dung, thời lượng và âm thanh bên phải" width="88%"></p>
+**Which AI writes the scenes?** LumReels picks the first one available:
-**AI nào dựng cảnh?** LumReels tự chọn theo thứ tự:
+1. `api`: an `ANTHROPIC_API_KEY` in `.env`.
+2. `claude`: [Claude Code](https://claude.com/claude-code) installed on the machine.
+3. `agent`: neither, so the job waits for an outside agent to submit the scene over MCP/REST, then renders it.
-1. `api`: có `ANTHROPIC_API_KEY` trong `.env`.
-2. `claude`: máy có [Claude Code](https://claude.com/claude-code).
-3. `agent`: không có cả hai thì job dừng chờ, agent bên ngoài viết cảnh qua MCP/REST rồi render.
+**Voice-over** is optional. Music and sound effects need nothing extra.
-**Giọng đọc** là tuỳ chọn: `pip install vieneu` (chạy trên máy) hoặc `pip install edge-tts`. Nhạc và tiếng động không cần cài gì thêm.
+```bash
+pip install kokoro soundfile # English voices, runs locally
+pip install vieneu # Vietnamese voices, runs locally
+pip install edge-tts # online fallback for both
+```
-## Nối với AI agent
+## Connect an AI agent
```jsonc
-// claude_desktop_config.json, .mcp.json, hay cấu hình MCP của agent bất kỳ
+// claude_desktop_config.json, .mcp.json, or any MCP client config
{
"mcpServers": {
- "lumreels": { "command": "node", "args": ["/đường/dẫn/lumreels/mcp/server.mjs"] }
+ "lumreels": { "command": "node", "args": ["/path/to/lumreels/mcp/server.mjs"] }
}
}
```
-Agent có các tool `list_templates`, `rewrite_script`, `create_video`, `submit_scene`, `preview_job`, `render_job`, `set_audio`… Ví dụ nhờ agent: *"Mỗi sáng 7h lấy tin mới, dựng video mẫu 009 dài 30 giây rồi để vào Drive."*
+Tools include `list_templates`, `rewrite_script`, `create_video`, `submit_scene`, `preview_job`, `render_job` and `set_audio`. Try asking your agent: *"Every morning at 7, take the latest news, make a 30-second video in style 009 and put it in my Drive."*
```bash
-node cli.mjs make --template 009 --content nd.txt --duration 30 --at 2026-12-01T07:00
+node cli.mjs make --template 009 --content script.txt --duration 30 --at 2026-12-01T07:00
```
-Hướng dẫn có hình từng bước: **[docs/HUONG-DAN-KET-NOI-AGENT.md](docs/HUONG-DAN-KET-NOI-AGENT.md)**.
-
-## Cách hoạt động
+## How it works
```
-nội dung + mẫu ──► PROMPT (guidance của mẫu + luật viết cảnh)
- │
- ▼
- AI viết scene/index.html ──► xem thử 16 khung + kiểm font ──► AI tự sửa
- │
- ▼
- HyperFrames (Chrome headless) render 1080×1920 30fps ──► trộn nhạc · tiếng động · giọng ──► out.mp4
+content + style ──► PROMPT (style guidance + scene-authoring rules)
+ │
+ ▼
+ AI writes scene/index.html ──► 16-frame preview + font check ──► AI fixes
+ │
+ ▼
+ HyperFrames (headless Chrome) renders 1080×1920 @ 30fps ──► mix music · SFX · voice ──► out.mp4
```
-Mỗi cảnh là một trang HTML khai báo `VideoScene.define({ duration, render(t) })`: khung hình là hàm thuần theo `t`, nên dùng được DOM, SVG, Canvas, shader WebGL và Three.js mà vẫn render đúng từng khung.
+Each scene is an HTML page that declares `VideoScene.define({ duration, render(t) })`. Every frame is a pure function of `t`, so DOM, SVG, Canvas, WebGL shaders and Three.js all render frame-exact.
+
+## Docs
-## Tài liệu
+The detailed docs are in Vietnamese for now. Machine translation handles them well, and the code and CLI flags are self-explanatory.
| | |
|---|---|
-| [docs/CHI-TIET.md](docs/CHI-TIET.md) | Biến `.env`, luồng job, CLI/REST/MCP đầy đủ, cây thư mục, âm thanh, **thêm mẫu mới** |
-| [docs/HUONG-DAN-KET-NOI-AGENT.md](docs/HUONG-DAN-KET-NOI-AGENT.md) | Nối Claude, ChatGPT/Codex, hẹn giờ, xuất Google Drive |
-| [engine/AUTHORING.md](engine/AUTHORING.md) | Luật viết cảnh cho AI (hoặc cho người) |
-| [templates/GUIDANCE-SPEC.md](templates/GUIDANCE-SPEC.md) | Khuôn 12 mục để mô tả một phong cách |
+| [docs/CHI-TIET.md](docs/CHI-TIET.md) | `.env` options, job lifecycle, full CLI/REST/MCP reference, folder layout, audio, **adding a new style** |
+| [docs/HUONG-DAN-KET-NOI-AGENT.md](docs/HUONG-DAN-KET-NOI-AGENT.md) | Connecting Claude, ChatGPT/Codex, scheduling, Google Drive export (with screenshots) |
+| [engine/AUTHORING.md](engine/AUTHORING.md) | Scene-authoring rules for the AI (or for you) |
+| [templates/GUIDANCE-SPEC.md](templates/GUIDANCE-SPEC.md) | The 12-section format for describing a style |
-## Giấy phép
+## License
-[MIT](LICENSE). Render bằng [HyperFrames](https://www.npmjs.com/package/hyperframes) (Apache-2.0); font OFL. Repo không kèm video tham chiếu: mẫu nào cũng chỉ là bản mô tả phong cách bằng chữ, mọi chữ trên video lấy từ nội dung của mày.
+[MIT](LICENSE). Rendering by [HyperFrames](https://www.npmjs.com/package/hyperframes) (Apache-2.0); fonts under OFL; English TTS by [Kokoro](https://huggingface.co/hexgrad/Kokoro-82M) (Apache-2.0). The repo ships no reference videos. Each style is only a written description, and all on-screen text comes from your content. Third-party licenses: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
-<p align="center"><sub>Làm bởi Lumtek · Việt Nam</sub></p>
+<p align="center"><sub>Made by Lumtek · Vietnam</sub></p>
diff --git a/README.vi.md b/README.vi.md
new file mode 100644
index 0000000..0572333
--- /dev/null
+++ b/README.vi.md
@@ -0,0 +1,113 @@
+<p align="center">
+ <a href="https://reels.lumtek.net"><img src="docs/img/readme/banner.jpg" alt="LumReels: gõ nội dung, chọn 1 mẫu phong cách, AI viết cảnh bằng code và xuất video dọc 9:16" width="100%"></a>
+</p>
+
+<p align="center"><a href="README.md">English</a> · <b>Tiếng Việt</b></p>
+
+<p align="center">
+ <a href="https://reels.lumtek.net"><img alt="Xem các mẫu" src="https://img.shields.io/badge/xem_m%E1%BA%ABu-reels.lumtek.net-ff4f6d?style=for-the-badge"></a>
+ <a href="LICENSE"><img alt="MIT" src="https://img.shields.io/badge/license-MIT-a46bff?style=for-the-badge"></a>
+ <img alt="Node 22+" src="https://img.shields.io/badge/node-22%2B-3c873a?style=for-the-badge&logo=node.js&logoColor=white">
+ <img alt="MCP" src="https://img.shields.io/badge/MCP-s%E1%BA%B5n_s%C3%A0ng-111?style=for-the-badge">
+</p>
+
+<p align="center">
+ <b>LumReels</b> biến một đoạn chữ thành video dọc 1080×1920 theo một trong hơn 100 mẫu phong cách (mỗi tuần thêm mẫu mới).<br>
+ Không cắt ghép footage, không kho template kéo thả: AI đọc bản mô tả phong cách rồi <b>viết một cảnh HTML/SVG/WebGL mới</b>, máy render ra MP4 có nhạc, tiếng động và giọng đọc tiếng Việt hoặc tiếng Anh.
+</p>
+
+<p align="center">
+ <img src="docs/img/readme/demo.webp" alt="6 video dựng bằng LumReels: hố đen, mười chất liệu, poster risograph, sa mạc xà cừ, game PS1, vệt sáng phơi sáng" width="100%">
+ <br><sub>Hố đen giả định · Mười chất liệu · Poster risograph · Sa mạc xà cừ · Game 3D PS1 · Vệt sáng phơi sáng</sub>
+</p>
+
+---
+
+## Làm được gì
+
+| | |
+|---|---|
+| 🎬 **Hơn 100 mẫu phong cách** | Faceless, quảng cáo, đa phong cách: shader vũ trụ, 3D low-poly, giấy cắt, pixel 8-bit, risograph, terminal… Mỗi mẫu là một file mô tả bằng chữ (màu, font, bố cục, nhịp theo giây), không kèm video gốc. |
+| ✍️ **AI viết cảnh, không ghép template** | Claude viết cảnh mới cho từng nội dung, tự xem ảnh xem thử và sửa. Nút **Viết lại kịch bản** xếp chữ của bạn vào đúng ô của mẫu. |
+| 🔊 **Âm thanh trọn gói** | 6 kiểu nhạc nền, ~30 tiếng động gắn theo chuyển động, giọng đọc tiếng Việt (VieNeu) và tiếng Anh (Kokoro), đều chạy trên máy, dự phòng edge-tts; chuẩn −14 LUFS. Đổi nhạc/giọng không phải dựng lại hình. |
+| 🤖 **Cho AI agent gọi thẳng** | MCP server, CLI và REST. Claude, Codex hay agent bất kỳ: tạo video, gửi cảnh, xem thử, render, hẹn giờ, chép MP4 ra Google Drive. |
+| ⏱️ **3 giây tới 10 phút** | Gõ `90` hoặc `1:30`. Video dài tự chia cảnh, mỗi khung là hàm thuần theo thời gian nên render ổn định. |
+| 🇻🇳 **Tiếng Việt chuẩn** | 25 họ font có dấu tiếng Việt, tự kiểm font thiếu dấu, chữ tràn khung, chữ quá nhỏ trước khi render. |
+
+## Thư viện mẫu
+
+<p align="center">
+ <a href="https://reels.lumtek.net"><img src="docs/img/readme/mau.jpg" alt="Lưới mẫu phong cách của LumReels" width="100%"></a>
+ <br><sub>Mẫu nào cũng đã dựng thử bằng chính LumReels. Bấm để xem video có tiếng trên <a href="https://reels.lumtek.net">reels.lumtek.net</a>.</sub>
+</p>
+
+## Chạy thử trong 2 phút
+
+Cần **Node 22+**, **ffmpeg** và **Google Chrome**.
+
+```bash
+git clone https://github.com/lumtekvn/lumreels.git
+cd lumreels
+npm install # tự chép three/gsap và 25 họ font tiếng Việt
+npm start # mở http://127.0.0.1:4400
+```
+
+Chọn mẫu → gõ nội dung → chọn thời lượng, nhạc, giọng → **Tạo video**.
+
+<p align="center"><img src="docs/img/ui-luoi-mau.png" alt="Giao diện LumReels: lưới mẫu bên trái, nội dung, thời lượng và âm thanh bên phải" width="88%"></p>
+
+**AI nào dựng cảnh?** LumReels tự chọn theo thứ tự:
+
+1. `api`: có `ANTHROPIC_API_KEY` trong `.env`.
+2. `claude`: máy có [Claude Code](https://claude.com/claude-code).
+3. `agent`: không có cả hai thì job dừng chờ, agent bên ngoài viết cảnh qua MCP/REST rồi render.
+
+**Giọng đọc** là tuỳ chọn: `pip install vieneu` (tiếng Việt), `pip install kokoro soundfile` (tiếng Anh), đều chạy trên máy; `pip install edge-tts` để dự phòng qua mạng. Nhạc và tiếng động không cần cài gì thêm.
+
+## Nối với AI agent
+
+```jsonc
+// claude_desktop_config.json, .mcp.json, hay cấu hình MCP của agent bất kỳ
+{
+ "mcpServers": {
+ "lumreels": { "command": "node", "args": ["/đường/dẫn/lumreels/mcp/server.mjs"] }
+ }
+}
+```
+
+Agent có các tool `list_templates`, `rewrite_script`, `create_video`, `submit_scene`, `preview_job`, `render_job`, `set_audio`… Ví dụ nhờ agent: *"Mỗi sáng 7h lấy tin mới, dựng video mẫu 009 dài 30 giây rồi để vào Drive."*
+
+```bash
+node cli.mjs make --template 009 --content nd.txt --duration 30 --at 2026-12-01T07:00
+```
+
+Hướng dẫn có hình từng bước: **[docs/HUONG-DAN-KET-NOI-AGENT.md](docs/HUONG-DAN-KET-NOI-AGENT.md)**.
+
+## Cách hoạt động
+
+```
+nội dung + mẫu ──► PROMPT (guidance của mẫu + luật viết cảnh)
+ │
+ ▼
+ AI viết scene/index.html ──► xem thử 16 khung + kiểm font ──► AI tự sửa
+ │
+ ▼
+ HyperFrames (Chrome headless) render 1080×1920 30fps ──► trộn nhạc · tiếng động · giọng ──► out.mp4
+```
+
+Mỗi cảnh là một trang HTML khai báo `VideoScene.define({ duration, render(t) })`: khung hình là hàm thuần theo `t`, nên dùng được DOM, SVG, Canvas, shader WebGL và Three.js mà vẫn render đúng từng khung.
+
+## Tài liệu
+
+| | |
+|---|---|
+| [docs/CHI-TIET.md](docs/CHI-TIET.md) | Biến `.env`, luồng job, CLI/REST/MCP đầy đủ, cây thư mục, âm thanh, **thêm mẫu mới** |
+| [docs/HUONG-DAN-KET-NOI-AGENT.md](docs/HUONG-DAN-KET-NOI-AGENT.md) | Nối Claude, ChatGPT/Codex, hẹn giờ, xuất Google Drive |
+| [engine/AUTHORING.md](engine/AUTHORING.md) | Luật viết cảnh cho AI (hoặc cho người) |
+| [templates/GUIDANCE-SPEC.md](templates/GUIDANCE-SPEC.md) | Khuôn 12 mục để mô tả một phong cách |
+
+## Giấy phép
+
+[MIT](LICENSE). Render bằng [HyperFrames](https://www.npmjs.com/package/hyperframes) (Apache-2.0); font OFL. Repo không kèm video tham chiếu: mẫu nào cũng chỉ là bản mô tả phong cách bằng chữ, mọi chữ trên video lấy từ nội dung của bạn. Giấy phép bên thứ ba (GSAP không phải MIT): [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+
+<p align="center"><sub>Làm bởi Lumtek · Việt Nam</sub></p>
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000..d27df01
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,28 @@
+# Third-party notices
+
+LumReels' own source code is released under the [MIT License](LICENSE).
+It depends on the third-party software below. These packages are **not bundled in this repository**: `npm install` / `pip install` downloads them, and each one stays under its own license.
+
+| Package | Used for | License |
+|---|---|---|
+| [hyperframes](https://www.npmjs.com/package/hyperframes) | Headless Chrome frame capture and encoding | Apache-2.0 |
+| [three](https://threejs.org) | 3D scenes | MIT |
+| [gsap](https://gsap.com) | Timeline bridge required by HyperFrames | [GSAP Standard "No Charge" License](https://gsap.com/standard-license) (free, including commercial use; **not** an OSI open-source license) |
+| [puppeteer-core](https://pptr.dev) | Browser control | Apache-2.0 |
+| [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) | MCP server | MIT |
+| [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript) | Claude API mode | MIT |
+| [zod](https://zod.dev) | Schema validation | MIT |
+| [@fontsource/*](https://fontsource.org) (25 families) | Fonts copied into `engine/fonts` at install | SIL Open Font License 1.1 (fonts), MIT (packaging) |
+| [Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M) via `pip install kokoro` | Optional English voices | Apache-2.0 |
+| VieNeu via `pip install vieneu` | Optional Vietnamese voices | Apache-2.0 (package); model weights per their model card |
+| [edge-tts](https://github.com/rany2/edge-tts) | Optional online voice fallback (uses Microsoft's online TTS service) | LGPL-3.0 (package); service subject to Microsoft's terms |
+| ffmpeg, Google Chrome | Installed separately by the user | Their own licenses |
+
+## Files in this repository that are not MIT
+
+- `site/src/fonts/be-vietnam-pro-*.woff2`: Be Vietnam Pro, © The Be Vietnam Pro Project Authors, SIL Open Font License 1.1 (see `site/src/fonts/OFL.txt`).
+
+## Content
+
+- Style guidance files (`templates/guidance/*.md`) are original written descriptions of visual styles. They contain no third-party footage or images.
+- Thumbnails (`templates/thumbs/`) and demo media are frames and renders produced by LumReels itself.
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.md
index 9f55923..288c61f 100644
--- a/docs/CHI-TIET.md
+++ b/docs/CHI-TIET.md
@@ -95,17 +95,20 @@ Repo **không kèm video tham chiếu**. Ví dụ trong guidance (tên quán, kh
6. Render xong, tạo ảnh đại diện cho lưới mẫu: `node scripts/make-thumbs.mjs 106 <jobId>` → `templates/thumbs/106.webp` (khung giây 5,5; đổi bằng `--at 4`, ghi đè bằng `--force`). Commit file này cùng guidance. `sync-catalog.mjs` liệt kê mẫu nào còn thiếu ảnh.
## Âm thanh
-Cảnh kèm `scene/audio.json` (AUTHORING §9): engine tự tổng hợp nhạc nền + tiếng động (DSP thuần JS), đọc lời tiếng Việt (VieNeu, dự phòng edge-tts), trộn −14 LUFS rồi ghép vào MP4 lúc render. Đã render rồi: `node cli.mjs audio <jobId>`. Ghép file có sẵn: `render.mjs --audio file`.
+Cảnh kèm `scene/audio.json` (AUTHORING §9): engine tự tổng hợp nhạc nền + tiếng động (DSP thuần JS), đọc lời tiếng Việt (VieNeu, dự phòng edge-tts) hoặc tiếng Anh (Kokoro, dự phòng edge-tts), trộn −14 LUFS rồi ghép vào MP4 lúc render. Đã render rồi: `node cli.mjs audio <jobId>`. Ghép file có sẵn: `render.mjs --audio file`.
Nhạc và tiếng động không cần cài gì thêm (chỉ ffmpeg). **Giọng đọc là tuỳ chọn**, cần Python 3.10+:
```
pip install vieneu # giọng Việt chạy trên máy (mặc định, ~1 GB mô hình tải lần đầu; máy yếu đọc 1 câu mất 1–10 phút)
-pip install edge-tts # dự phòng khi chưa có VieNeu (cần mạng)
+pip install kokoro soundfile # giọng Anh chạy trên máy (Kokoro-82M, Apache-2.0, ~330 MB tải lần đầu; CPU đọc 1 câu vài giây)
+pip install edge-tts # dự phòng khi chưa có VieNeu/Kokoro hoặc chúng lỗi (cần mạng)
```
-Thiếu VieNeu thì UI ghi "Cài giọng đọc: pip install vieneu" và tự dùng edge-tts. `LUMREELS_PYTHON` = đường dẫn python nếu không phải `python`.
+Thiếu VieNeu thì UI ghi "Cài giọng đọc: pip install vieneu", thiếu Kokoro thì ghi "Cài giọng Anh: pip install kokoro soundfile", và tự dùng edge-tts cùng ngôn ngữ, cùng giới. Kokoro không cần cài espeak-ng riêng (gói `espeakng-loader` kèm sẵn); lần chạy đầu tự tải mô hình từ Hugging Face và gói `en_core_web_sm`. Máy có torch cũ (< 2.6) thì giữ `transformers<4.48` (`pip install "transformers>=4.40,<4.48"`), vì transformers 5 tắt torch cũ và Kokoro không chạy. `LUMREELS_PYTHON` = đường dẫn python nếu không phải `python`.
Chọn âm thanh khi tạo job: `{ audio: { music: <style>|"auto"|"none", voice: <tên giọng>|"auto"|"none", sfx: true|false } }` (REST `POST /api/jobs`, MCP `create_video`, CLI `make --music chill --voice "Trúc Ly" --no-sfx`). `auto` = AI chọn theo §9 guidance.
Đổi tiếng video đã dựng (không dựng lại hình): UI "Âm thanh · đổi nhạc, giọng đọc" trong mỗi video, REST `POST /api/jobs/:id/audio {music, voice, sfx}`, MCP `set_audio`, CLI `node cli.mjs audio <jobId> --music epic --voice "Thiện Minh"`. `out.mp4` luôn là bản mới nhất, bản cũ ở `versions/out-<n>.mp4` (+ `audio-<n>.json`), hình không tiếng ở `out.silent.mp4`. Chọn giọng mà chưa có lời → AI viết lời ngắn (api → claude, như "Viết lại kịch bản").
-Lựa chọn + nghe thử: `GET /api/audio/options`, `GET /api/audio/preview?style=chill`, `GET /api/audio/preview?voice=Hải Đăng&text=...` (cache trong `engine/audio/samples/`). Nghe toàn bộ tiếng động: `engine/audio/samples/sfx-all.wav` (sinh lại: `node engine/audio/samples.mjs`).
+**Giọng Anh** (`lang: "en"`, Kokoro): `af_heart` Heart (US, nữ, mặc định) · `af_bella` Bella (US, nữ) · `am_michael` Michael (US, nam) · `am_fenrir` Fenrir (US, nam) · `bf_emma` Emma (UK, nữ) · `bm_george` George (UK, nam). Giọng Kokoro khác cũng nhận (`am_puck`…). Dự phòng edge-tts: `af_*` → `en-US-AvaMultilingualNeural`, `am_*` → `en-US-AndrewNeural`, `bf_*` → `en-GB-SoniaNeural`, `bm_*` → `en-GB-RyanNeural`; chọn thẳng được bằng `edge:en-US-AvaMultilingualNeural`…
+Mỗi giọng trong `GET /api/audio/options` có `lang: "vi"|"en"`; UI nhóm theo Tiếng Việt / English. `voice: "auto"` đoán ngôn ngữ từ nội dung (có chữ có dấu tiếng Việt → vi, không thì en); en thì AI viết lời đọc tiếng Anh, giọng mặc định `af_heart`. Chọn giọng khác ngôn ngữ với lời đang có (vd lời Việt, chọn `am_michael`) → bỏ lời cũ, AI viết lại đúng ngôn ngữ giọng. Lời tiếng Anh: engine tự đọc số kiểu Anh (`12%` → twelve percent, `$4.99` → four dollars and ninety-nine cents, `$1.5M` → one point five million dollars, `2024` → twenty twenty-four, `1st`, `the 1990s`).
+Lựa chọn + nghe thử: `GET /api/audio/options`, `GET /api/audio/preview?style=chill`, `GET /api/audio/preview?voice=Hải Đăng&text=...`, `?voice=af_heart` (câu mẫu tiếng Anh) (cache trong `engine/audio/samples/`). Nghe toàn bộ tiếng động: `engine/audio/samples/sfx-all.wav` (sinh lại: `node engine/audio/samples.mjs`).
## Engine
HyperFrames (npm `hyperframes`, Apache-2.0) chạy bằng CLI cục bộ, tắt telemetry/kiểm cập nhật. Khoá render toàn máy của HyperFrames được tắt và thay bằng hàng chờ riêng (`LUMREELS_HF_SLOTS`). Runtime `scene.js` đăng ký `window.__timelines.main` cho HyperFrames và xuất `window.__scene.seek(t)` để có thể đổi bộ chụp nếu cần.
diff --git a/docs/img/readme/banner-en.jpg b/docs/img/readme/banner-en.jpg
new file mode 100644
index 0000000..f352393
Binary files /dev/null and b/docs/img/readme/banner-en.jpg differ
diff --git a/engine/AUTHORING.md b/engine/AUTHORING.md
index 8723a13..acfd2e8 100644
--- a/engine/AUTHORING.md
+++ b/engine/AUTHORING.md
@@ -190,7 +190,7 @@ VideoScene.define({
- Viết `NaN`/`undefined` ra màn hình khi t ngoài khoảng: luôn kẹp tiến độ bằng `prog()`.
## 9. Âm thanh (`scene/audio.json`)
-Video không có file này thì ra **không tiếng**. Viết kèm `audio.json` cạnh `index.html`; engine tự tổng hợp nhạc + tiếng động (DSP thuần JS, không file tải về), đọc lời bằng VieNeu (dự phòng edge-tts), trộn, chuẩn hoá −14 LUFS, ghép AAC 192k vào MP4 lúc render. Đã render rồi thì chỉ cần `node cli.mjs audio <jobId>` (không render lại hình).
+Video không có file này thì ra **không tiếng**. Viết kèm `audio.json` cạnh `index.html`; engine tự tổng hợp nhạc + tiếng động (DSP thuần JS, không file tải về), đọc lời bằng VieNeu (tiếng Việt) hoặc Kokoro (tiếng Anh), dự phòng edge-tts, trộn, chuẩn hoá −14 LUFS, ghép AAC 192k vào MP4 lúc render. Đã render rồi thì chỉ cần `node cli.mjs audio <jobId>` (không render lại hình).
```json
{
"music": { "style": "upbeat", "gain": -8 },
@@ -226,7 +226,8 @@ Guidance ghi "không nhạc" thì bỏ `music` (để `null`).
```
- Mỗi dòng 1 câu ngắn, đọc bắt đầu đúng `t`. Ước lượng ~4,5 âm tiết/giây: câu phải đọc xong trước `t` của dòng sau và trước hết video (engine cảnh báo nếu lấn).
- Chữ viết bình thường (`Lumfin`, `5 triệu`); engine tự đổi cách đọc tên riêng ("Lum phin"). Cần đọc khác chữ thì thêm `"say": "..."`.
-- `speaker` (VieNeu): nam `Hải Đăng` (mặc định), `Thiện Minh` (kể chuyện, trầm), `Xuân Vĩnh`, `Quốc Tuấn`; nữ `Trúc Ly`, `Ngọc Huyền`, `Đoan Trang`, `Mai Anh` (tin tức). `"engine": "edge"` để dùng edge-tts (cần mạng).
+- `speaker` tiếng Việt (VieNeu): nam `Hải Đăng` (mặc định), `Thiện Minh` (kể chuyện, trầm), `Xuân Vĩnh`, `Quốc Tuấn`; nữ `Trúc Ly`, `Ngọc Huyền`, `Đoan Trang`, `Mai Anh` (tin tức). `"engine": "edge"` để dùng edge-tts (cần mạng).
+- **Nội dung tiếng Anh** (không có chữ có dấu tiếng Việt): viết lời bằng tiếng Anh (~2,7 từ/giây), `speaker` tiếng Anh (Kokoro): nữ `af_heart` (US, mặc định), `af_bella` (US), `bf_emma` (UK); nam `am_michael` (US, trầm), `am_fenrir` (US, khoẻ), `bm_george` (UK, kể chuyện). Bỏ `speaker` thì engine tự chọn theo ngôn ngữ của lời. Số, `%`, `$`, năm viết bình thường (`$4.99`, `12%`, `2024`), engine tự đọc kiểu Anh. Cài: `pip install kokoro soundfile`; thiếu hoặc lỗi thì tự chuyển edge-tts tiếng Anh.
## 10. Bài học từ 104 cảnh thử
Rút từ đợt dựng thử toàn bộ thư viện mẫu (mỗi mẫu 1 cảnh 8 giây, render trên máy không có GPU rời). Guidance của mẫu nào còn ghi khác mục này thì làm theo mục này.
diff --git a/engine/audio/mix.mjs b/engine/audio/mix.mjs
index 313bea3..d86dec0 100644
--- a/engine/audio/mix.mjs
+++ b/engine/audio/mix.mjs
@@ -9,7 +9,8 @@ import path from 'node:path';
import { run, probe } from '../lib.mjs';
import { SFX_NAMES, writeSfx } from './sfx.mjs';
import { MUSIC_STYLES, writeMusic } from './music.mjs';
-import { synthVoice, DEFAULT_VOICE } from './voice.mjs';
+import { synthVoice, detectLang } from './voice.mjs';
+import { voiceEngine, defaultVoiceFor } from './prefs.mjs';
import { hashStr } from './dsp.mjs';
export const TARGET_LUFS = -14;
@@ -43,11 +44,13 @@ export function validateAudioSpec(spec) {
return spec;
}
-async function ff(args, what) {
+async function ff(args, what, durS = 60) {
// ffmpeg đôi khi treo ở graph sidechain → giới hạn 3 phút, thử lại 1 lần
let r;
- for (let i = 0; i < 2; i++) {
- r = await run('ffmpeg', ['-y', '-hide_banner', '-nostats', '-nostdin', ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeoutMs: 180000 });
+ // treo hiếm gặp (~1/12 lần, ffmpeg 9 trên Windows): chờ ngắn theo độ dài video rồi thử lại, tối đa 3 lượt
+ const timeoutMs = Math.round(30000 + durS * 1500);
+ for (let i = 0; i < 3; i++) {
+ r = await run('ffmpeg', ['-y', '-hide_banner', '-nostats', '-nostdin', '-filter_complex_threads', '1', ...args], { stdio: ['ignore', 'pipe', 'pipe'], timeoutMs });
if (r.code === 0) break;
}
if (r.code !== 0) throw new Error(`${what} lỗi: ${r.out.slice(-800)}`);
@@ -83,7 +86,11 @@ export async function buildMix(sceneDir, { duration, workDir, log = console.log,
const lines = (spec.voice?.lines || []).slice().sort((a, b) => a.t - b.t);
let voice = [];
if (lines.length) {
- voice = await synthVoice(lines, workDir, { engine: spec.voice.engine || 'vieneu', voice: spec.voice.speaker || DEFAULT_VOICE, log });
+ // thiếu speaker → giọng mặc định theo ngôn ngữ của lời (có dấu tiếng Việt → Hải Đăng, không thì af_heart);
+ // thiếu engine → suy từ tên giọng (af_heart → kokoro, edge:… → edge, còn lại vieneu; máy thiếu thì edge-tts)
+ const speaker = spec.voice.speaker || defaultVoiceFor(detectLang(lines.map((l) => l.text).join(' ')));
+ const ve = spec.voice.engine ? { engine: spec.voice.engine, speaker } : voiceEngine(speaker);
+ voice = await synthVoice(lines, workDir, { engine: ve.engine, voice: ve.speaker, log });
voice.forEach((v, i) => {
const end = v.t + v.dur, next = i + 1 < voice.length ? voice[i + 1].t : duration;
if (end > next + 0.05) warn(`lời "${v.text}" dài ${v.dur.toFixed(2)}s, từ ${v.t}s tới ${end.toFixed(2)}s, lấn sang ${i + 1 < voice.length ? `câu sau (${next}s)` : `hết video (${duration.toFixed(2)}s)`}. Rút gọn câu hoặc dời mốc.`);
@@ -103,9 +110,9 @@ export async function buildMix(sceneDir, { duration, workDir, log = console.log,
if (!fs.existsSync(mf)) writeMusic(spec.music.style, mf, duration, seed);
const k = addInput(mf);
const g = spec.music.gain ?? (vLabels.length ? -12 : -6);
- chains.push(`[${k}:a]${fmt},volume=${g}dB[mus]`);
+ chains.push(`[${k}:a]${fmt},volume=${g}dB,apad,atrim=0:${duration.toFixed(4)}[mus]`);
if (vLabels.length) {
- chains.push(`${vLabels.join('')}amix=inputs=${vLabels.length}:normalize=0:duration=longest,asplit=2[vbus][vkey]`);
+ chains.push(`${vLabels.join('')}amix=inputs=${vLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)},asplit=2[vbus][vkey]`); // cùng độ dài với nhạc: tránh sidechain chờ nhau mà treo
chains.push(`[mus][vkey]sidechaincompress=threshold=0.05:ratio=3:attack=25:release=450:makeup=1[musd]`);
mixLabels.push('[musd]', '[vbus]');
} else mixLabels.push('[mus]');
@@ -126,13 +133,13 @@ export async function buildMix(sceneDir, { duration, workDir, log = console.log,
// tiền trộn (float, chưa chuẩn hoá) dài đúng duration
const pre = path.join(workDir, 'premix.wav');
const graph = [...chains, `${mixLabels.join('')}amix=inputs=${mixLabels.length}:normalize=0:duration=longest,apad,atrim=0:${duration.toFixed(4)}[out]`].join(';');
- await ff([...inputs, '-filter_complex', graph, '-map', '[out]', '-t', duration.toFixed(4), '-ar', '48000', '-c:a', 'pcm_f32le', pre], 'trộn âm thanh');
+ await ff([...inputs, '-filter_complex', graph, '-map', '[out]', '-t', duration.toFixed(4), '-ar', '48000', '-c:a', 'pcm_f32le', pre], 'trộn âm thanh', duration);
// loudnorm 2 lượt → −14 LUFS
- const m = parseLoudnorm(await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-'], 'đo loudness'));
+ const m = parseLoudnorm(await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:print_format=json`, '-f', 'null', '-'], 'đo loudness', duration));
const wav = path.join(workDir, 'mix.wav');
await ff(['-i', pre, '-af', `loudnorm=I=${TARGET_LUFS}:TP=-1.5:LRA=11:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true,atrim=0:${duration.toFixed(4)}`,
- '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', wav], 'chuẩn hoá loudness');
+ '-ar', '48000', '-ac', '2', '-c:a', 'pcm_s16le', wav], 'chuẩn hoá loudness', duration);
return { wav, warnings, voice: voice.map(({ t, text, spoken, dur }) => ({ t, text, spoken, dur })) };
}
@@ -140,7 +147,7 @@ export async function buildMix(sceneDir, { duration, workDir, log = console.log,
export async function muxAudio(videoIn, wav, outFile, duration) {
const tmp = outFile.replace(/\.mp4$/i, '.mux.tmp.mp4');
await ff(['-i', videoIn, '-i', wav, '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2',
- '-t', duration.toFixed(4), '-movflags', '+faststart', tmp], 'ghép âm thanh vào MP4');
+ '-t', duration.toFixed(4), '-movflags', '+faststart', tmp], 'ghép âm thanh vào MP4', duration);
fs.renameSync(tmp, outFile);
return outFile;
}
diff --git a/engine/audio/prefs.mjs b/engine/audio/prefs.mjs
index 6965573..1e403bb 100644
--- a/engine/audio/prefs.mjs
+++ b/engine/audio/prefs.mjs
@@ -3,6 +3,7 @@
// "auto" = để AI chọn theo §9 guidance và viết scene/audio.json. Lúc trộn, tuỳ chọn cố định ghi đè audio.json.
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';
const PY = process.env.LUMREELS_PYTHON || 'python';
@@ -15,29 +16,49 @@ export const VIENEU_VOICES = [
['Trúc Ly', 'nữ', 'Bắc', 'tự nhiên'], ['Ngọc Huyền', 'nữ', 'Bắc', 'tự nhiên'], ['Đoan Trang', 'nữ', 'Bắc', 'tự nhiên'],
['Mai Anh', 'nữ', 'Bắc', 'tin tức'], ['Ngọc Linh', 'nữ', 'Bắc', 'kể chuyện'], ['Quỳnh Anh', 'nữ', 'Bắc', 'đọc truyện'],
['Ngọc Trân', 'nữ', 'Trung', 'tự nhiên'], ['Thùy Dung', 'nữ', 'Nam', 'tin tức'], ['Mỹ Duyên', 'nữ', 'Nam', 'đọc truyện'],
-].map(([name, gender, region, style]) => ({ id: name, name, gender, region, style, engine: 'vieneu' }));
+].map(([name, gender, region, style]) => ({ id: name, name, gender, region, style, engine: 'vieneu', lang: 'vi' }));
+/** Giọng Anh Kokoro-82M (chạy trên máy). Đã nghe thử + whisper nghe lại đúng chữ (xem docs/CHI-TIET.md mục Âm thanh). */
+export const KOKORO_VOICES = [
+ ['af_heart', 'Heart', 'nữ', 'US', 'ấm, tự nhiên (mặc định)'], ['af_bella', 'Bella', 'nữ', 'US', 'sáng, nhiều cảm xúc'],
+ ['am_michael', 'Michael', 'nam', 'US', 'trầm, điềm đạm'], ['am_fenrir', 'Fenrir', 'nam', 'US', 'khoẻ, dứt khoát'],
+ ['bf_emma', 'Emma', 'nữ', 'UK', 'nhẹ nhàng, rõ chữ'], ['bm_george', 'George', 'nam', 'UK', 'trầm, kể chuyện'],
+].map(([id, n, gender, region, style]) => ({ id, name: `${n} (${region}, ${gender})`, gender, region, style, engine: 'kokoro', lang: 'en' }));
export const EDGE_VOICES = [
- { id: 'edge:vi-VN-HoaiMyNeural', name: 'Hoài My (edge-tts)', gender: 'nữ', region: 'Bắc', style: 'cần mạng', engine: 'edge' },
- { id: 'edge:vi-VN-NamMinhNeural', name: 'Nam Minh (edge-tts)', gender: 'nam', region: 'Bắc', style: 'cần mạng', engine: 'edge' },
+ { id: 'edge:vi-VN-HoaiMyNeural', name: 'Hoài My (edge-tts)', gender: 'nữ', region: 'Bắc', style: 'cần mạng', engine: 'edge', lang: 'vi' },
+ { id: 'edge:vi-VN-NamMinhNeural', name: 'Nam Minh (edge-tts)', gender: 'nam', region: 'Bắc', style: 'cần mạng', engine: 'edge', lang: 'vi' },
+ { id: 'edge:en-US-AvaMultilingualNeural', name: 'Ava (US, nữ, edge-tts)', gender: 'nữ', region: 'US', style: 'cần mạng', engine: 'edge', lang: 'en' },
+ { id: 'edge:en-US-AndrewNeural', name: 'Andrew (US, nam, edge-tts)', gender: 'nam', region: 'US', style: 'cần mạng', engine: 'edge', lang: 'en' },
+ { id: 'edge:en-GB-SoniaNeural', name: 'Sonia (UK, nữ, edge-tts)', gender: 'nữ', region: 'UK', style: 'cần mạng', engine: 'edge', lang: 'en' },
+ { id: 'edge:en-GB-RyanNeural', name: 'Ryan (UK, nam, edge-tts)', gender: 'nam', region: 'UK', style: 'cần mạng', engine: 'edge', lang: 'en' },
];
export const VOICE_SAMPLE_TEXT = 'Xin chào, đây là giọng đọc thử của Lumfin.';
+export const VOICE_SAMPLE_TEXT_EN = 'Hi there, this is a voice sample from Lumfin. Save twelve percent more every month.';
+/** Câu nghe thử theo ngôn ngữ của giọng. */
+export const sampleTextFor = (voice) => (voiceLang(voice) === 'en' ? VOICE_SAMPLE_TEXT_EN : VOICE_SAMPLE_TEXT);
+export { voiceLang, detectLang };
const hasPyModule = (m) => spawnSync(PY, ['-c', `import importlib.util,sys;sys.exit(0 if importlib.util.find_spec('${m}') else 1)`], { windowsHide: true, timeout: 20000 }).status === 0;
let tools = null;
-/** Máy có VieNeu / edge-tts không (kiểm 1 lần mỗi tiến trình). */
+/** Máy có VieNeu / Kokoro / edge-tts không (kiểm 1 lần mỗi tiến trình). */
export function ttsAvailable(refresh = false) {
- if (!tools || refresh) tools = { vieneu: hasPyModule('vieneu'), edge: hasPyModule('edge_tts') };
+ if (!tools || refresh) tools = { vieneu: hasPyModule('vieneu'), kokoro: hasPyModule('kokoro') && hasPyModule('soundfile'), edge: hasPyModule('edge_tts') };
return tools;
}
-/** { engine, speaker } cho 1 giá trị voice. VieNeu không có trên máy → rơi về edge-tts cùng giới. */
+/** Giọng mặc định cho 1 ngôn ngữ ('vi' | 'en'). */
+export const defaultVoiceFor = (lang) => (lang === 'en' ? DEFAULT_VOICE_EN : DEFAULT_VOICE);
+
+/** { 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) {
- if (String(voice).startsWith('edge:')) return { engine: 'edge', speaker: voice.slice(5) };
+ const lang = voiceLang(voice);
+ 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 };
if (!ttsAvailable().vieneu) {
const v = VIENEU_VOICES.find((x) => x.id === voice);
- return { engine: 'edge', speaker: v?.gender === 'nữ' ? 'vi-VN-HoaiMyNeural' : 'vi-VN-NamMinhNeural' };
+ return { engine: 'edge', speaker: v?.gender === 'nữ' ? 'vi-VN-HoaiMyNeural' : 'vi-VN-NamMinhNeural', lang };
}
- return { engine: 'vieneu', speaker: voice };
+ return { engine: 'vieneu', speaker: voice, lang };
}
/** Chuẩn hoá + kiểm tuỳ chọn. Thiếu trường → auto / auto / true. */
@@ -47,8 +68,11 @@ 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';
- const known = ['auto', 'none', ...VIENEU_VOICES.map((v) => v.id), ...EDGE_VOICES.map((v) => v.id)];
- if (!known.includes(voice) && !/^edge:vi-VN-\w+Neural$/.test(voice)) throw new Error(`audio.voice "${voice}" không có (auto | none | tên giọng: ${VIENEU_VOICES.map((v) => v.id).join(', ')})`);
+ 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)) {
+ throw new Error(`audio.voice "${voice}" không có (auto | none | tên giọng: ${[...VIENEU_VOICES, ...KOKORO_VOICES].map((v) => v.id).join(', ')})`);
+ }
const sfx = a.sfx === undefined ? true : !(a.sfx === false || a.sfx === 'false' || a.sfx === 0 || a.sfx === '0');
return { music, voice, sfx };
}
@@ -88,12 +112,20 @@ export function applyAudioPrefs(spec, prefs) {
/** Danh sách cho UI / API. */
export function audioOptions() {
const t = ttsAvailable();
+ const edge = (lang) => (t.edge ? EDGE_VOICES.filter((v) => v.lang === lang) : []);
+ const hints = [
+ t.vieneu ? null : `Cài giọng đọc: pip install vieneu${t.edge ? ' (đang dùng edge-tts, cần mạng)' : ' (hoặc pip install edge-tts)'}`,
+ t.kokoro ? null : `Cài giọng Anh: pip install kokoro soundfile${t.edge ? ' (đang dùng edge-tts, cần mạng)' : ''}`,
+ ].filter(Boolean);
return {
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 : []), ...(t.edge ? EDGE_VOICES : [])],
- vieneu: t.vieneu, edgeTts: t.edge,
- hint: t.vieneu ? null : `Cài giọng đọc: pip install vieneu${t.edge ? ' (đang dùng edge-tts, cần mạng)' : ' (hoặc pip install edge-tts)'}`,
- sampleText: VOICE_SAMPLE_TEXT,
+ ...(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,
+ hints,
+ sampleText: VOICE_SAMPLE_TEXT, sampleTextEn: VOICE_SAMPLE_TEXT_EN,
};
}
diff --git a/engine/audio/tts_kokoro.py b/engine/audio/tts_kokoro.py
new file mode 100644
index 0000000..cd4beb7
--- /dev/null
+++ b/engine/audio/tts_kokoro.py
@@ -0,0 +1,56 @@
+"""Đọc danh sách câu tiếng Anh bằng Kokoro-82M (Apache-2.0, chạy trên máy), nạp mô hình 1 lần.
+
+ python engine/audio/tts_kokoro.py <jobs.json>
+ jobs.json: [{"text": "...", "out": "đường/dẫn.wav", "voice": "af_heart"}, ...]
+Giọng bắt đầu bằng "a" = giọng Mỹ, "b" = giọng Anh (af_/am_/bf_/bm_ = nữ/nam). WAV 24 kHz mono.
+In 1 dòng JSON mỗi câu xong: {"out": ..., "ok": true} hoặc {"out": ..., "ok": false, "error": ...}.
+Cài: pip install kokoro soundfile (lần đầu tải ~330 MB mô hình từ Hugging Face).
+"""
+import json
+import os
+import sys
+import warnings
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+warnings.filterwarnings("ignore")
+os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
+
+REPO = "hexgrad/Kokoro-82M"
+SR = 24000
+
+
+def main():
+ with open(sys.argv[1], encoding="utf-8") as f:
+ jobs = json.load(f)
+ import numpy as np
+ import soundfile as sf
+ from kokoro import KModel, KPipeline
+
+ model = KModel(repo_id=REPO).eval()
+ pipes = {}
+
+ def pipe(voice):
+ code = voice[:1] if voice[:1] in ("a", "b") else "a"
+ if code not in pipes:
+ pipes[code] = KPipeline(lang_code=code, repo_id=REPO, model=model)
+ return pipes[code]
+
+ for j in jobs:
+ voice = j.get("voice") or "af_heart"
+ err = None
+ try:
+ parts = []
+ for r in pipe(voice)(j["text"], voice=voice, speed=float(j.get("speed") or 1)):
+ if r.audio is not None:
+ # .tolist(): torch cũ build với numpy 1.x không .numpy() được trên numpy 2
+ parts.append(np.asarray(r.audio.tolist(), dtype=np.float32))
+ if not parts:
+ raise RuntimeError("Kokoro không ra âm thanh")
+ sf.write(j["out"], np.concatenate(parts), SR)
+ except Exception as e: # noqa: BLE001
+ err = f"{type(e).__name__}: {e}"
+ print(json.dumps({"out": j["out"], "ok": err is None, "error": err}, ensure_ascii=False), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine/audio/voice.mjs b/engine/audio/voice.mjs
index 547cf64..18adc2a 100644
--- a/engine/audio/voice.mjs
+++ b/engine/audio/voice.mjs
@@ -1,4 +1,5 @@
-// Giọng đọc tiếng Việt: VieNeu (chạy trên máy, mặc định) → edge-tts (dự phòng, cần mạng).
+// Giọng đọc. Tiếng Việt: VieNeu (chạy trên máy, mặc định) → edge-tts (dự phòng, cần mạng).
+// Tiếng Anh: Kokoro-82M (chạy trên máy) → edge-tts tiếng Anh (dự phòng).
// Mỗi câu ra 1 WAV 48 kHz mono đã cắt lặng đầu/cuối và đưa RMS về −16 dBFS; có cache theo nội dung.
import fs from 'node:fs';
import path from 'node:path';
@@ -9,8 +10,25 @@ import { readWav, writeWav, normalizeRms, SR } from './dsp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
export const DEFAULT_VOICE = 'Hải Đăng';
+export const DEFAULT_VOICE_EN = 'af_heart';
const PY = process.env.LUMREELS_PYTHON || 'python';
+/** Giọng Kokoro: a/b = Mỹ/Anh, f/m = nữ/nam (af_heart, bm_george…). */
+export const isKokoroVoice = (v) => /^[ab][fm]_[a-z]+$/.test(String(v));
+/** Ngôn ngữ của 1 giọng: Kokoro và edge en-* → 'en', còn lại 'vi'. */
+export function voiceLang(v) {
+ const s = String(v || '').replace(/^edge:/, '');
+ return isKokoroVoice(s) || /^en-[A-Z]{2}-/.test(s) ? 'en' : 'vi';
+}
+// Chữ cái chỉ tiếng Việt có (không tính á/é/í… vì tiếng Tây Ban Nha/Pháp cũng có).
+const VI_CHARS = /[ăâđêôơưạảãấầẩẫậắằẳẵặẹẻẽếềểễệỉĩịọỏõốồổỗộớờởỡợụủũứừửữựỳỵỷỹ]/i;
+/** Đoán ngôn ngữ nội dung: có dấu tiếng Việt → 'vi', không thì 'en'. Trống → 'vi'. */
+export function detectLang(text) {
+ const s = String(text || '');
+ if (VI_CHARS.test(s)) return 'vi';
+ return /[a-z]{2}/i.test(s) ? 'en' : 'vi';
+}
+
// Cách đọc cho TTS; chữ trên màn hình giữ nguyên. "Lum phin" là cách duy nhất whisper nghe ra đúng "Lumfin" (đã thử 7 cách).
const SAY = [
[/\blumfin\.net\b/gi, 'Lum phin chấm nét'],
@@ -19,17 +37,87 @@ const SAY = [
[/&/g, ' và '],
[/(\d+(?:[.,]\d+)?)\s*%/g, '$1 phần trăm'],
];
-export function toSpeech(text) {
+
+// ---------- tiếng Anh: số, %, $, năm ----------
+const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
+ 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
+const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
+const SCALES = [[1e12, 'trillion'], [1e9, 'billion'], [1e6, 'million'], [1e3, 'thousand']];
+function under1000(n) {
+ const h = Math.floor(n / 100), r = n % 100, out = [];
+ if (h) out.push(ONES[h], 'hundred');
+ if (r) out.push(r < 20 ? ONES[r] : TENS[Math.floor(r / 10)] + (r % 10 ? '-' + ONES[r % 10] : ''));
+ return out.join(' ');
+}
+/** Số nguyên ≥ 0 → chữ tiếng Anh (tới hàng nghìn tỷ). */
+export function intToEnglish(n) {
+ n = Math.floor(Math.abs(n));
+ if (n < 20) return ONES[n];
+ const out = [];
+ for (const [v, w] of SCALES) if (n >= v) { out.push(under1000(Math.floor(n / v)), w); n %= v; }
+ if (n) out.push(under1000(n));
+ return out.join(' ');
+}
+/** "3.5" → "three point five"; "1,200" → "one thousand two hundred". */
+function numToEnglish(str) {
+ const [i, d] = String(str).replace(/,/g, '').split('.');
+ const w = intToEnglish(Number(i || 0));
+ return d ? `${w} point ${[...d].map((c) => ONES[+c]).join(' ')}` : w;
+}
+/** Năm 1100–2099 kiểu Anh: 1999 → nineteen ninety-nine, 2005 → two thousand five, 2024 → twenty twenty-four. */
+function yearToEnglish(y) {
+ const hi = Math.floor(y / 100), lo = y % 100;
+ if (y >= 2000 && y < 2010) return intToEnglish(y);
+ if (lo === 0) return `${intToEnglish(hi)} hundred`;
+ return `${intToEnglish(hi)} ${lo < 10 ? 'oh ' + ONES[lo] : intToEnglish(lo)}`;
+}
+const MULT = { k: 'thousand', K: 'thousand', m: 'million', M: 'million', b: 'billion', B: 'billion', bn: 'billion', tn: 'trillion' };
+const ORD = { one: 'first', two: 'second', three: 'third', five: 'fifth', eight: 'eighth', nine: 'ninth', twelve: 'twelfth' };
+function ordinal(n) {
+ const w = intToEnglish(n), parts = w.split(/([ -])/), last = parts.pop();
+ const o = ORD[last] || (last.endsWith('y') ? last.slice(0, -1) + 'ieth' : last + 'th');
+ return parts.join('') + o;
+}
+const NUM = String.raw`\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?`;
+const SAY_EN = [
+ [/&/g, ' and '],
+ [/\+/g, ' plus '],
+ // $1.5M, $20k, $5, $4.99
+ [new RegExp(String.raw`\$\s?(${NUM})(?:\s?(bn|tn|[kKmMbB]|thousand|million|billion|trillion)\b)?`, 'g'), (_, n, m) => {
+ if (m) return `${numToEnglish(n)} ${MULT[m] || m} dollars`;
+ const [i, c] = n.replace(/,/g, '').split('.');
+ const d = `${intToEnglish(+i)} ${+i === 1 ? 'dollar' : 'dollars'}`;
+ return c && +c ? `${d} and ${intToEnglish(+c.padEnd(2, '0').slice(0, 2))} cents` : d;
+ }],
+ [new RegExp(String.raw`(${NUM})\s?%`, 'g'), (_, n) => `${numToEnglish(n)} percent`],
+ [/\b(\d+)(st|nd|rd|th)\b/gi, (_, n) => ordinal(+n)],
+ [/\b(1[1-9]\d0|20\d0)s\b/g, (_, y) => yearToEnglish(+y).replace(/y$/, 'ies').replace(/(hundred|thousand)$/, '$1s')], // the 1990s
+ [/\b(\d{2})s\b/g, (_, n) => (+n % 10 ? `${intToEnglish(+n)}s` : intToEnglish(+n).replace(/y$/, 'ies'))], // the 90s
+ [/\b(1[1-9]\d\d|20\d\d)\b(?![.,]\d)/g, (_, y) => yearToEnglish(+y)],
+ [new RegExp(String.raw`\b(${NUM})\s?(bn|tn|[kKmMbB])\b`, 'g'), (_, n, m) => `${numToEnglish(n)} ${MULT[m]}`],
+ [new RegExp(String.raw`(${NUM})`, 'g'), (_, n) => numToEnglish(n)],
+];
+/** Chữ trên màn hình → chữ đưa vào TTS. lang 'en' đọc số/%, $, năm kiểu Anh; 'vi' giữ cách đọc tiếng Việt. */
+export function toSpeech(text, lang = 'vi') {
let s = String(text);
- for (const [re, rep] of SAY) s = s.replace(re, rep);
+ for (const [re, rep] of lang === 'en' ? SAY_EN : SAY) s = s.replace(re, rep);
return s.replace(/[*_#]/g, '').replace(/\s+/g, ' ').trim();
}
/** Giọng edge-tts tương ứng khi phải dự phòng. */
const EDGE = { female: 'vi-VN-HoaiMyNeural', male: 'vi-VN-NamMinhNeural' };
+// Kokoro → edge-tts cùng giọng vùng + giới: a/b = Mỹ/Anh, f/m = nữ/nam.
+const EDGE_EN = { af: 'en-US-AvaMultilingualNeural', am: 'en-US-AndrewNeural', bf: 'en-GB-SoniaNeural', bm: 'en-GB-RyanNeural' };
// Giọng nữ có sẵn của VieNeu v3 Turbo (còn lại là nam): Trúc Ly, Mai Anh, Thùy Dung, Ngọc Huyền, Ngọc Trân,
// Ngọc Linh, Đoan Trang, Thục Đoan, Mỹ Duyên, Quỳnh Anh, Kim Thanh. Nam hay dùng: Hải Đăng (mặc định), Thiện Minh (kể chuyện).
const FEMALE = /trúc ly|mai anh|thùy dung|ngọc|đoan|mỹ duyên|quỳnh anh|kim thanh/i;
+/** Tên giọng edge-tts dùng khi dự phòng cho 1 giọng bất kỳ. */
+export function edgeVoiceFor(voice) {
+ const v = String(voice || '');
+ if (/^[a-z]{2}-[A-Z]{2}-\w+Neural$/.test(v)) return v;
+ if (isKokoroVoice(v)) return EDGE_EN[v.slice(0, 2)];
+ return FEMALE.test(v) ? EDGE.female : EDGE.male;
+}
async function toWav48(src, dst) {
const r = await run('ffmpeg', ['-y', '-v', 'error', '-i', src, '-ac', '1', '-ar', String(SR), '-c:a', 'pcm_s16le', dst]);
@@ -49,9 +137,9 @@ function trimNormalize(file) {
/**
* lines: [{t, text, say?}] → [{t, text, file, dur}]. workDir chứa cache voice-<hash>.wav.
- * engine: 'vieneu' | 'edge'. Lỗi VieNeu thì tự chuyển edge-tts.
+ * engine: 'vieneu' | 'kokoro' | 'edge'. Lỗi VieNeu/Kokoro thì tự chuyển edge-tts (cùng ngôn ngữ, cùng giới).
*/
-// Mỗi lúc chỉ 1 lượt TTS (VieNeu nạp mô hình nặng): xếp hàng trong tiến trình.
+// 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();
export function synthVoice(...args) {
const p = ttsChain.then(() => synthVoiceNow(...args));
@@ -60,28 +148,36 @@ export function synthVoice(...args) {
}
async function synthVoiceNow(lines, workDir, { engine = 'vieneu', voice = DEFAULT_VOICE, log = console.log } = {}) {
fs.mkdirSync(workDir, { recursive: true });
+ if (engine === 'vieneu' && isKokoroVoice(voice)) engine = 'kokoro';
+ const lang = voiceLang(voice);
const items = lines.map((l) => {
- const spoken = toSpeech(l.say || l.text);
+ const spoken = toSpeech(l.say || l.text, lang);
const h = crypto.createHash('sha1').update(`${engine}|${voice}|${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));
- if (todo.length && engine === 'vieneu') {
+ 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 jf = path.join(workDir, 'tts-jobs.json');
fs.writeFileSync(jf, JSON.stringify(raw, null, 1));
- log(`giọng: VieNeu "${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, 'tts_vieneu.py'), jf], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
+ log(`giọng: ${label} "${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++) {
- if (fs.existsSync(raw[i].out)) { await toWav48(raw[i].out, todo[i].file); fs.rmSync(raw[i].out, { force: true }); }
+ if (fs.existsSync(raw[i].out)) { await toWav48(raw[i].out, todo[i].file); fs.rmSync(raw[i].out, { force: true }); } else miss++;
+ }
+ 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(' ');
+ 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)));
}
- if (r.code !== 0) log('CẢNH BÁO: VieNeu lỗi, chuyển edge-tts. ' + r.out.slice(-400));
}
for (const it of items.filter((x) => !fs.existsSync(x.file))) {
- const ev = /^vi-VN-\w+Neural$/.test(voice) ? voice : FEMALE.test(voice) ? EDGE.female : EDGE.male, mp3 = it.file.replace(/\.wav$/, '.mp3');
+ 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' } });
- if (r.code !== 0 || !fs.existsSync(mp3)) throw new Error('Không tạo được giọng đọc (VieNeu và edge-tts đều lỗi): ' + r.out.slice(-300));
+ if (r.code !== 0 || !fs.existsSync(mp3)) throw new Error(`Không tạo được giọng đọc (${LOCAL ? LOCAL[0] + ' và ' : ''}edge-tts đều lỗi): ` + r.out.slice(-300));
await toWav48(mp3, it.file); fs.rmSync(mp3, { force: true });
}
const out = [];
diff --git a/generator/audio-job.mjs b/generator/audio-job.mjs
index 0d997b4..1a6b19f 100644
--- a/generator/audio-job.mjs
+++ b/generator/audio-job.mjs
@@ -12,7 +12,7 @@ import { readJob, jobDir, guidancePath, logTo, exportOutput } from './jobs.mjs';
import { resolveRewriteEngine } from './rewrite.mjs';
import { probe } from '../engine/lib.mjs';
import { addAudio, loadAudioSpec, videoDuration } from '../engine/audio/mix.mjs';
-import { normalizeAudioPrefs, applyAudioPrefs, styleFromGuidance, voiceEngine } from '../engine/audio/prefs.mjs';
+import { normalizeAudioPrefs, applyAudioPrefs, styleFromGuidance, voiceEngine, detectLang } from '../engine/audio/prefs.mjs';
const AI_TIMEOUT_MS = 90_000;
const busy = new Set();
@@ -36,20 +36,21 @@ export function listVersions(id) {
return out;
}
-/** Hỏi AI viết lời đọc ngắn khớp mốc. Trả [{t, text}]. */
-export async function writeNarration(job, spec, duration, { log = () => {} } = {}) {
+/** Hỏi AI viết lời đọc ngắn khớp mốc. lang 'vi' | 'en' (mặc định: đoán từ nội dung). Trả [{t, text}]. */
+export async function writeNarration(job, spec, duration, { log = () => {}, lang = detectLang(job.content) } = {}) {
+ const en = lang === 'en';
const dir = jobDir(job.id);
const brief = fs.existsSync(path.join(dir, 'brief.json')) ? fs.readFileSync(path.join(dir, 'brief.json'), 'utf8').slice(0, 6000) : '';
const g = fs.existsSync(guidancePath(job.templateId)) ? fs.readFileSync(guidancePath(job.templateId), 'utf8') : '';
const s9 = (g.match(/##\s*9\.[^\n]*\n([\s\S]*?)(\n##\s|$)/) || [])[1] || '';
const marks = (spec?.sfx || []).map((s) => `${s.t}s ${s.name}`).join(', ');
- const prompt = `Viết LỜI ĐỌC tiếng Việt cho 1 video dọc ${duration.toFixed(1)} giây đã dựng xong (không đổi hình).
+ const prompt = `Viết LỜI ĐỌC ${en ? 'TIẾNG ANH (English)' : 'tiếng Việt'} cho 1 video dọc ${duration.toFixed(1)} giây đã dựng xong (không đổi hình).
Trả ĐÚNG 1 khối JSON, không thêm gì: {"lines":[{"t":<giây bắt đầu>,"text":"<câu>"}]}
Luật:
-- 1 đến ${duration > 12 ? 5 : 3} câu, mỗi câu ngắn. Tốc độ đọc ~4,5 âm tiết/giây: câu phải đọc xong trước "t" câu sau và trước giây ${(duration - 0.3).toFixed(1)}.
+- 1 đến ${duration > 12 ? 5 : 3} câu, mỗi câu ngắn. Tốc độ đọc ${en ? '~2,7 từ tiếng Anh/giây' : '~4,5 âm tiết/giây'}: câu phải đọc xong trước "t" câu sau và trước giây ${(duration - 0.3).toFixed(1)}.
- Câu đầu bắt đầu trong 0,1–0,6s. Đặt "t" trùng mốc chuyển động chính (mốc tiếng động: ${marks || 'không có'}).
-- Chỉ dùng ý, số, tên thương hiệu có trong nội dung/brief; không bịa số. Tiếng Việt đủ dấu, viết số bằng chữ số bình thường.
+- Chỉ dùng ý, số, tên thương hiệu có trong nội dung/brief; không bịa số. ${en ? 'Viết bằng tiếng Anh tự nhiên kiểu người bản xứ (nội dung gốc tiếng Việt thì dịch ý), viết số bằng chữ số bình thường ($5, 12%, 2024).' : 'Tiếng Việt đủ dấu, viết số bằng chữ số bình thường.'}
- Có tên thương hiệu/CTA thì câu cuối nói tên đó.
${s9 ? `- Gợi ý giọng/lời của mẫu: ${s9.trim().slice(0, 600)}` : ''}
@@ -125,9 +126,14 @@ export async function reAudio(id, prefs, { log, exportOut = false } = {}) {
const cur = loadAudioSpec(scene);
let spec = applyAudioPrefs(cur, { ...p, fallbackStyle });
const duration = await videoDuration(silent);
- if (p.voice !== 'none' && p.voice !== 'auto' && !spec?.voice?.lines?.length) {
- const lines = await writeNarration(job, spec || cur, duration, { log: L });
- const ve = voiceEngine(p.voice);
+ const ve = p.voice !== 'none' && p.voice !== 'auto' ? voiceEngine(p.voice) : null;
+ // giọng khác ngôn ngữ với lời đang có (vd lời Việt mà chọn giọng Anh) → bỏ lời cũ, AI viết lại đúng ngôn ngữ giọng
+ if (ve && spec?.voice?.lines?.length && detectLang(spec.voice.lines.map((l) => l.text).join(' ')) !== ve.lang) {
+ L(`lời đọc đang có khác ngôn ngữ giọng "${p.voice}" (${ve.lang}), nhờ AI viết lại`);
+ spec = { ...spec, voice: null };
+ }
+ if (ve && !spec?.voice?.lines?.length) {
+ const lines = await writeNarration(job, spec || cur, duration, { log: L, lang: ve.lang });
spec = { ...(spec || { music: null, sfx: [] }), voice: { speaker: ve.speaker, engine: ve.engine, lines } };
L(`lời đọc AI viết: ${lines.map((l) => `${l.t}s "${l.text}"`).join(' | ')}`);
}
diff --git a/generator/prompt.mjs b/generator/prompt.mjs
index 0febbf8..d6c8428 100644
--- a/generator/prompt.mjs
+++ b/generator/prompt.mjs
@@ -2,19 +2,23 @@
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';
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)));
/** Tuỳ chọn âm thanh người dùng đã chọn (job.audio = {music, voice, sfx}) → luật thêm cho audio.json. */
-function audioRule(a) {
+function audioRule(a, content = '') {
if (!a || typeof a !== 'object') return '';
const r = [];
+ // ngôn ngữ lời đọc: giọng cụ thể → theo giọng; "auto" → đoán từ nội dung (có dấu tiếng Việt → vi, không thì en)
+ const lang = a.voice && a.voice !== 'auto' && a.voice !== 'none' ? voiceLang(a.voice) : detectLang(content);
if (a.music === 'none') r.push('KHÔNG nhạc nền: `"music": null`');
else if (a.music && a.music !== 'auto') r.push(`nhạc nền dùng đúng \`"style": "${a.music}"\``);
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}"\`` : ''}`);
return r.length ? ` - Người dùng đã chọn âm thanh: ${r.join('; ')}.
` : '';
}
@@ -64,7 +68,7 @@ ${job.content}
- **Đúng kỹ thuật**: frontmatter \`technique\` của guidance có \`three\` hoặc \`webgl-shader\` thì PHẢI dựng phần đó bằng Three.js / shader WebGL thật (./lib/vendor/three.module.js), không hạ xuống 2D phẳng. Chỉ được đổi nếu ghi rõ lý do trong brief.json (trường \`technique_note\`).
- Font: chỉ dùng font trong AUTHORING §4, theo bảng ánh xạ ở đó.
- **Âm thanh (bắt buộc)**: ghi kèm \`scene/audio.json\` theo AUTHORING §9 — thiếu file này video ra không tiếng. Chọn \`music.style\` hợp §9 "Âm thanh" của guidance; 6–15 sfx cho 8 giây (video dài hơn thì tăng theo tỉ lệ) đặt \`t\` đúng các mốc chuyển động mày vừa viết trong \`render(t)\`; \`voice\` chỉ khi frontmatter guidance có \`narration: true\`, mỗi câu ngắn, đọc xong trước mốc câu sau. Hệ thống tự trộn và ghép lúc render.
-${audioRule(job.audio)}
+${audioRule(job.audio, job.content)}
Chỉ được: đọc file, ghi/sửa file trong thư mục job này, chạy đúng 2 lệnh preview/render ở trên. Không cài gì, không gọi mạng.${longNote}
---
diff --git a/mcp/server.mjs b/mcp/server.mjs
index 1da5308..8765b92 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -21,7 +21,7 @@ import { audioOptions } from '../engine/audio/prefs.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"'),
+ 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'),
sfx: z.boolean().optional(),
});
@@ -208,7 +208,7 @@ server.registerTool('set_audio', {
description: [
'Trộn tiếng mới (nhạc / giọng đọc / tiếng động) và ghép vào hình ĐÃ DỰNG, không dựng lại hình. out.mp4 thành bản mới nhất, bản cũ giữ ở versions/out-<n>.mp4.',
'Trường bỏ trống = giữ như hiện tại. Chọn giọng mà video chưa có lời đọc → AI viết 1–3 câu ngắn. Gọi không tham số (chỉ jobId) để xem lựa chọn + các bản đang có.',
- 'VieNeu (giọng trên máy) đọc mất 1–10 phút tuỳ máy; chờ tối đa ~100 giây, lâu hơn thì gọi get_job.',
+ 'Chọn giọng Anh (af_heart…) thì AI viết lời tiếng Anh. VieNeu (giọng trên máy) đọc mất 1–10 phút tuỳ máy, Kokoro (giọng Anh) vài giây/câu; chờ tối đa ~100 giây, lâu hơn thì gọi get_job.',
].join(' '),
inputSchema: { jobId: z.string().regex(/^[\w-]{1,80}$/), music: audioSchema.shape.music, voice: audioSchema.shape.voice, sfx: audioSchema.shape.sfx },
}, async ({ jobId, music, voice, sfx }) => {
diff --git a/server/public/audio-panel.js b/server/public/audio-panel.js
index 7bc3d24..f6e175e 100644
--- a/server/public/audio-panel.js
+++ b/server/public/audio-panel.js
@@ -27,7 +27,7 @@
if (playingBtn === btn) { player.pause(); setBtn(btn, 'idle'); playingBtn = null; return; }
if (playingBtn) { player.pause(); setBtn(playingBtn, 'idle'); }
playingBtn = btn; setBtn(btn, 'load');
- if (note) note.textContent = url.includes('voice=') ? 'Đang tạo giọng mẫu… (VieNeu lần đầu có thể mất vài phút)' : '';
+ if (note) note.textContent = url.includes('voice=') ? 'Đang tạo giọng mẫu… (lần đầu nạp mô hình có thể mất vài phút)' : '';
try {
const r = await fetch(url);
if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'không tạo được bản nghe thử');
@@ -50,8 +50,16 @@
const keep = keepLabel ? '<option value="">Giữ như hiện tại</option>' : '';
const music = (opts?.music || [{ id: 'auto', name: 'Tự chọn theo mẫu' }]).map((m) =>
`<option value="${esc(m.id)}" ${cur.music === m.id ? 'selected' : ''}>${esc(m.id === 'auto' || m.id === 'none' ? m.name : m.id + ' — ' + (m.desc || ''))}</option>`).join('');
- const voices = (opts?.voices || [{ id: 'auto', name: 'Theo mẫu' }]).map((v) =>
- `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(v.engine ? `${v.name} · ${v.gender}, ${v.region} · ${v.style}` : v.name)}</option>`).join('');
+ // giọng nhóm theo ngôn ngữ (<optgroup> Tiếng Việt / English); auto/none đứng đầu, không nhóm.
+ // Giọng Anh đã có vùng + giới trong tên ("Heart (US, nữ)") nên chỉ thêm kiểu giọng.
+ const vOpt = (v) => `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(!v.engine ? v.name
+ : v.lang === 'en' ? `${v.name} · ${v.style}` : `${v.name} · ${v.gender}, ${v.region} · ${v.style}`)}</option>`;
+ const allV = opts?.voices || [{ id: 'auto', name: 'Theo mẫu' }];
+ 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);
+ return vs.length ? `<optgroup label="${esc(l.name)}">${vs.map(vOpt).join('')}</optgroup>` : '';
+ }).join('');
return `
<label class="field" for="${id}m">Nhạc nền</label>
<div class="ap-row"><select id="${id}m" data-ap="music">${keep}${music}</select>
@@ -60,7 +68,7 @@
<div class="ap-row"><select id="${id}v" data-ap="voice">${keep}${voices}</select>
<button type="button" class="ap-play" data-prev="voice" data-label="Nghe thử giọng đọc" aria-label="Nghe thử giọng đọc">${ICON_PLAY}</button></div>
<label class="ap-switch"><input type="checkbox" data-ap="sfx" ${cur.sfx === false ? '' : 'checked'} /><span class="ap-knob" aria-hidden="true"></span> Tiếng động gắn theo chuyển động</label>
- ${opts?.hint ? `<div class="hint ap-hint">${esc(opts.hint)}</div>` : ''}
+ ${(opts?.hints || (opts?.hint ? [opts.hint] : [])).map((h) => `<div class="hint ap-hint">${esc(h)}</div>`).join('')}
<div class="hint ap-note" aria-live="polite"></div>`;
}
function readControls(box) {
diff --git a/server/server.mjs b/server/server.mjs
index 7ac5341..b5a022e 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -11,7 +11,7 @@ import { findClaude } from '../generator/claude.mjs';
import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
import { config } from '../generator/config.mjs';
import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
-import { audioOptions, normalizeAudioPrefs, voiceEngine, VOICE_SAMPLE_TEXT } from '../engine/audio/prefs.mjs';
+import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { synthVoice } from '../engine/audio/voice.mjs';
@@ -26,8 +26,8 @@ async function audioPreviewFile(q) {
return f;
}
if (voice) {
- const text = String(q.get('text') || VOICE_SAMPLE_TEXT).trim().slice(0, 160);
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ử');
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) });
diff --git a/site/src/fonts/OFL.txt b/site/src/fonts/OFL.txt
new file mode 100644
index 0000000..d28526e
--- /dev/null
+++ b/site/src/fonts/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-ThinItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-ExtraLight.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-ExtraLightItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Light.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-LightItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Regular.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Italic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Medium.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-MediumItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-SemiBold.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-SemiBoldItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Bold.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-BoldItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-ExtraBold.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-ExtraBoldItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-Black.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro) BeVietnamPro-BlackItalic.ttf: Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.