Compare commits
15
Commits
18dbc9c8d3
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b9a8c420e | ||
|
|
898763eb74 | ||
|
|
6c04071bb5 | ||
|
|
d234b9658d | ||
|
|
370c869ad0 | ||
|
|
0fa0bcb44a | ||
|
|
a7a6f3e6b6 | ||
|
|
b37b9eb779 | ||
|
|
bd921b1ac5 | ||
|
|
6d64987d64 | ||
|
|
85b206f1cd | ||
|
|
7e5257429a | ||
|
|
736ec14d5b | ||
|
|
4ed4e23282 | ||
|
|
21d68e2294 |
No files matched your search
+116
-17
@@ -1,13 +1,16 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(live-caption LANGUAGES CXX)
|
||||
project(live-caption VERSION 0.1.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
|
||||
endif()
|
||||
|
||||
option(LC_BUILD_TESTS "构建单元测试" ON)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# llama.cpp / libmtmd 的搜索路径
|
||||
#
|
||||
@@ -25,7 +28,7 @@ foreach(_p
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
find_package(Qt6 REQUIRED COMPONENTS Core)
|
||||
find_package(Qt6 REQUIRED COMPONENTS Core Widgets Network)
|
||||
find_package(PkgConfig REQUIRED)
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
@@ -45,33 +48,58 @@ else()
|
||||
GIT_REPOSITORY https://github.com/ggml-org/llama.cpp.git
|
||||
GIT_TAG b9951
|
||||
FIND_PACKAGE_ARGS NAMES llama CONFIG)
|
||||
set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE)
|
||||
set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE)
|
||||
set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_MakeAvailable(llama)
|
||||
set(LC_LLAMA_TARGET llama)
|
||||
endif()
|
||||
|
||||
# --- mtmd:llama.pc 里没有,单独找 ---
|
||||
find_library(LC_MTMD_LIB NAMES mtmd
|
||||
HINTS /usr/lib/x86_64-linux-gnu/llama)
|
||||
find_library(LC_MTMD_LIB NAMES mtmd HINTS /usr/lib/x86_64-linux-gnu/llama)
|
||||
if(NOT LC_MTMD_LIB)
|
||||
message(FATAL_ERROR "找不到 libmtmd(应随 libllama0 一起安装)")
|
||||
endif()
|
||||
message(STATUS "mtmd: ${LC_MTMD_LIB}")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
add_executable(live-caption-cli
|
||||
src/main.cpp
|
||||
src/transcript.cpp
|
||||
src/qwen3asr.cpp
|
||||
src/audio.cpp
|
||||
# sherpa-onnx(X-ASR / zipformer / Nemotron 等流式 ONNX 模型)
|
||||
#
|
||||
# 注意:官方预编译库是用旧 C++ ABI 编译的,所以只能用它的 C API。
|
||||
# 安装:把官方的 sherpa-onnx-vX.Y.Z-linux-x64-shared.tar.bz2 解到某个目录,
|
||||
# 用 -DSHERPA_ONNX_ROOT=<dir> 指定(默认见下)。
|
||||
# ---------------------------------------------------------------------------
|
||||
set(SHERPA_ONNX_ROOT "$ENV{HOME}/.local/opt/sherpa-onnx" CACHE PATH "sherpa-onnx 安装目录")
|
||||
set(LC_HAS_SHERPA OFF)
|
||||
if(EXISTS "${SHERPA_ONNX_ROOT}/include/sherpa-onnx/c-api/c-api.h")
|
||||
find_library(LC_SHERPA_C_API NAMES sherpa-onnx-c-api
|
||||
HINTS "${SHERPA_ONNX_ROOT}/lib" REQUIRED)
|
||||
find_library(LC_SHERPA_ORT NAMES onnxruntime
|
||||
HINTS "${SHERPA_ONNX_ROOT}/lib" REQUIRED)
|
||||
set(LC_HAS_SHERPA ON)
|
||||
message(STATUS "sherpa-onnx: ${SHERPA_ONNX_ROOT}")
|
||||
else()
|
||||
message(WARNING "未找到 sherpa-onnx(${SHERPA_ONNX_ROOT}),流式 ONNX 后端将不可用")
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# core:全部业务逻辑,刻意不依赖 Qt(方便测试与复用)
|
||||
# ---------------------------------------------------------------------------
|
||||
add_library(livecaption_core STATIC
|
||||
src/core/transcript.cpp
|
||||
src/core/audio.cpp
|
||||
src/core/qwen3asr.cpp
|
||||
src/core/streamingasr.cpp
|
||||
src/core/livepipeline.cpp
|
||||
)
|
||||
|
||||
target_include_directories(live-caption-cli PRIVATE src)
|
||||
|
||||
target_link_libraries(live-caption-cli PRIVATE
|
||||
Qt6::Core
|
||||
if(LC_HAS_SHERPA)
|
||||
target_sources(livecaption_core PRIVATE src/core/sherpaasr.cpp)
|
||||
target_compile_definitions(livecaption_core PUBLIC LC_HAVE_SHERPA=1)
|
||||
target_include_directories(livecaption_core PRIVATE "${SHERPA_ONNX_ROOT}/include")
|
||||
target_link_libraries(livecaption_core PUBLIC ${LC_SHERPA_C_API} ${LC_SHERPA_ORT})
|
||||
endif()
|
||||
target_include_directories(livecaption_core PUBLIC src/core)
|
||||
target_link_libraries(livecaption_core PUBLIC
|
||||
Threads::Threads
|
||||
PkgConfig::SAMPLERATE
|
||||
PkgConfig::PULSE
|
||||
@@ -79,6 +107,77 @@ target_link_libraries(live-caption-cli PRIVATE
|
||||
${LC_MTMD_LIB}
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# models:模型注册表与存储(Qt;注册表编译进二进制)
|
||||
# ---------------------------------------------------------------------------
|
||||
add_library(livecaption_models STATIC
|
||||
src/models/modelstore.cpp
|
||||
src/models/modeldownloader.cpp
|
||||
)
|
||||
target_include_directories(livecaption_models PUBLIC src/models)
|
||||
target_link_libraries(livecaption_models PUBLIC Qt6::Core Qt6::Network)
|
||||
qt_add_resources(livecaption_models "registry"
|
||||
PREFIX "/"
|
||||
BASE "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
FILES data/models.json)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ui:悬浮窗与 Qt 适配层
|
||||
# ---------------------------------------------------------------------------
|
||||
add_library(livecaption_ui STATIC
|
||||
src/ui/captionwindow.cpp
|
||||
src/ui/livetranscriber.cpp
|
||||
src/ui/appsettings.cpp
|
||||
src/ui/settingsdialog.cpp
|
||||
)
|
||||
target_include_directories(livecaption_ui PUBLIC src/ui)
|
||||
target_link_libraries(livecaption_ui PUBLIC livecaption_core livecaption_models Qt6::Widgets)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 可执行程序
|
||||
# ---------------------------------------------------------------------------
|
||||
# GUI:悬浮字幕窗
|
||||
add_executable(live-caption apps/gui/main.cpp)
|
||||
target_include_directories(live-caption PRIVATE apps/common)
|
||||
target_link_libraries(live-caption PRIVATE livecaption_ui livecaption_models)
|
||||
|
||||
# CLI:文件 / 流式文件 / 命令行实时;不链接 Qt Widgets
|
||||
add_executable(live-caption-cli apps/cli/main.cpp)
|
||||
target_include_directories(live-caption-cli PRIVATE apps/common)
|
||||
target_link_libraries(live-caption-cli PRIVATE livecaption_core livecaption_models)
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_compile_options(live-caption-cli PRIVATE -Wall -Wextra -Wno-unused-parameter)
|
||||
foreach(_t livecaption_core livecaption_ui livecaption_models live-caption live-caption-cli)
|
||||
target_compile_options(${_t} PRIVATE -Wall -Wextra -Wno-unused-parameter)
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安装后的 RPATH
|
||||
#
|
||||
# 1) $ORIGIN/../<私有库目录>:打包时随包携带的 sherpa-onnx 运行时(lib/ 下的相对路径);
|
||||
# 2) llama / mtmd:发行版把这两个库放在 .../llama 子目录,而该目录不在 ld 的默认搜索
|
||||
# 路径里(ldconfig -p 里看不到),所以必须显式写进 RPATH,否则安装后起不来。
|
||||
# ---------------------------------------------------------------------------
|
||||
set(LC_PRIVATE_LIBDIR "lib/live-caption")
|
||||
set(_lc_install_rpath "\$ORIGIN/../${LC_PRIVATE_LIBDIR}")
|
||||
get_filename_component(_lc_llama_dir "${LC_MTMD_LIB}" DIRECTORY)
|
||||
if(IS_DIRECTORY "${_lc_llama_dir}")
|
||||
list(APPEND _lc_install_rpath "${_lc_llama_dir}")
|
||||
endif()
|
||||
set_target_properties(live-caption live-caption-cli PROPERTIES
|
||||
INSTALL_RPATH "${_lc_install_rpath}"
|
||||
INSTALL_RPATH_USE_LINK_PATH OFF)
|
||||
message(STATUS "安装后 RPATH: ${_lc_install_rpath}")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
if(LC_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安装与打包(CPack → .deb)
|
||||
# ---------------------------------------------------------------------------
|
||||
include(cmake/Packaging.cmake)
|
||||
@@ -1,7 +1,11 @@
|
||||
# live-caption
|
||||
|
||||
Linux 桌面实时字幕:采集系统正在播放的声音,实时转写成字幕显示(类似 Chrome 实时字幕)。
|
||||
技术栈:C++ / Qt6 / CMake / Qwen3-ASR(llama.cpp,纯 C++,无 Python 依赖)。
|
||||
|
||||
技术栈:C++ / Qt6 / CMake。推理后端两个,**全部纯 C++,运行时不需要 Python**:
|
||||
|
||||
- `llama`:llama.cpp / ggml + Qwen3-ASR 的 GGUF 模型(准确率高、语言最全);
|
||||
- `sherpa`:sherpa-onnx + 流式 ONNX 模型(zipformer / X-ASR / Nemotron,原生流式、CPU 占用低)。
|
||||
|
||||
## 当前进度
|
||||
|
||||
@@ -9,48 +13,133 @@ Linux 桌面实时字幕:采集系统正在播放的声音,实时转写成
|
||||
|---|---|---|
|
||||
| Phase 0 | 可行性验证(采集 / 模型 / CPU 实时性) | ✅ 见 [docs/phase0-verification.md](docs/phase0-verification.md) |
|
||||
| Phase 1 | 命令行原型(进程内推理 + monitor 采集 + 滑窗 + 稳定前缀) | ✅ 见 [experiments/phase1/README.md](experiments/phase1/README.md) |
|
||||
| Phase 2 | 原生流式解码(前缀回滚 + 滑窗,去掉 VAD) | 待做,见 [docs/phase2-streaming.md](docs/phase2-streaming.md) |
|
||||
| Phase 3 | Qt 悬浮字幕窗(折叠/展开、语言标签、置顶) | 待做 |
|
||||
| Phase 4 | 设置界面(模型切换、语言、字体、位置) | 待做 |
|
||||
| Phase 5 | Wayland 支持、打包、模型分发 | 待做 |
|
||||
| Phase 2 | 原生流式解码(切片 + 增量 KV 复用 + 前缀回滚) | ✅ 见 [docs/phase2-streaming.md](docs/phase2-streaming.md) |
|
||||
| Phase 3 | Qt 悬浮字幕窗(折叠/展开、语言标签、置顶、实时链路) | ✅ 见 [docs/phase3-caption-window.md](docs/phase3-caption-window.md) |
|
||||
| Phase 3.5 | 双后端(llama / sherpa)+ 模型注册表 + 流式 ONNX | ✅ 见 [docs/asr-backends.md](docs/asr-backends.md) |
|
||||
| Phase 4 | 全 GUI 可用:设置对话框、应用内下载、托盘、采集设备、完整性校验 | ✅ 见 [docs/gui.md](docs/gui.md) |
|
||||
| Phase 5 | Wayland 支持、打包、模型分发 | 部分(模型下载/分发已可用,见上) |
|
||||
|
||||
## 关键结论(Phase 0 实测)
|
||||
|
||||
- 系统播放音频可从默认输出的 monitor 源采集(PipeWire + pipewire-pulse,走 libpulse,兼容 PulseAudio)。
|
||||
- `Qwen3-ASR-0.6B` 在本机(i5-13420H,无独显)纯推理 RTF ≈ **0.19**,实时有充足余量。
|
||||
注意口径:这是 `llama-cli` 纯生成的数字;程序内走 mtmd 音频编码的实现实测 RTF ≈ **0.56**
|
||||
(见 [docs/asr-backends.md](docs/asr-backends.md) 的实测对比)。两者都远低于 1.0,够实时。
|
||||
- 模型与推理运行时**必须锁版本**:只有 ggml-org 官方 GGUF(`general.architecture = qwen3vl`)与系统 llama.cpp 兼容;社区的 Q4 量化用的是 `qwen3asr` / `qwen3_asr`,装不进去。
|
||||
- 转写原始输出为 `language <LANG><asr_text><正文>`,语言名正好用于 UI 的语言标签。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 准备模型(只需一次;网络可达 hf-mirror.com)
|
||||
B=https://hf-mirror.com/ggml-org/Qwen3-ASR-0.6B-GGUF/resolve/main
|
||||
aria2c -x16 -s16 -k4M -o Qwen3-ASR-0.6B-Q8_0.gguf "$B/Qwen3-ASR-0.6B-Q8_0.gguf"
|
||||
aria2c -x16 -s16 -k4M -o mmproj-Qwen3-ASR-0.6B-Q8_0.gguf "$B/mmproj-Qwen3-ASR-0.6B-Q8_0.gguf"
|
||||
|
||||
# 2. 构建
|
||||
# 1. 构建
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
|
||||
# 3. 单文件转写
|
||||
./build/live-caption-cli \
|
||||
--model Qwen3-ASR-0.6B-Q8_0.gguf \
|
||||
--mmproj mmproj-Qwen3-ASR-0.6B-Q8_0.gguf \
|
||||
--file some_16k_mono.wav
|
||||
# 2. 悬浮字幕窗:首次启动会打开设置对话框,在里面下载并选择模型
|
||||
./build/live-caption
|
||||
|
||||
# 4. 实时字幕
|
||||
./build/live-caption-cli \
|
||||
--model Qwen3-ASR-0.6B-Q8_0.gguf \
|
||||
--mmproj mmproj-Qwen3-ASR-0.6B-Q8_0.gguf
|
||||
# 完全通过 GUI 操作:
|
||||
# · 首次启动 → 设置对话框:下载模型 / 选择当前使用 / 选识别语言 / 采集设备 / 下载源与代理
|
||||
# · 点左上角的语言标签 → 再次打开设置
|
||||
# · 底部的「应用」= 应用但不关闭,方便实时预览(不透明度、字号等)
|
||||
# · 「校验完整性」= 重算 sha256,确认模型文件没有损坏
|
||||
# · 托盘图标:显示/隐藏字幕、设置、退出
|
||||
# · 窗口的 ✕ = 隐藏到托盘(用托盘菜单可以再显示回来)
|
||||
# 命令行参数仍保留,仅用于自动化测试(显式给出时覆盖设置),全部选项见 docs/cli.md
|
||||
|
||||
# 3. 也可以先用脚本把模型下到应用数据目录(不进 GUI)
|
||||
./scripts/fetch-models.sh # 列出模型与安装状态
|
||||
./scripts/fetch-models.sh zipformer-zh-2025 # 下载指定模型
|
||||
|
||||
# 4. 命令行:单文件转写 / 流式转写 / 无窗口实时
|
||||
./build/live-caption-cli --model M --mmproj MM --file some_16k_mono.wav
|
||||
./build/live-caption-cli --model M --mmproj MM --stream-file some_16k_mono.wav
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model zipformer-zh-2025 --cli-live
|
||||
|
||||
# 5. 单元测试(不需要模型,也不需要显示环境)
|
||||
ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
## 目录
|
||||
## 推理后端
|
||||
|
||||
支持两条后端,正常情况下**不用手动选**:GUI 会根据所选的模型自动决定用哪条
|
||||
(`data/models.json` 里每个模型都写了 `backend`)。命令行下可以用 `--asr-backend` 强制指定
|
||||
(详见 [docs/asr-backends.md](docs/asr-backends.md)):
|
||||
|
||||
- **`llama`(默认)**:llama.cpp/ggml + Qwen3-ASR 的 GGUF 模型 —— 准确率高、52 种语言,但每步成本随段落增长。
|
||||
- **`sherpa`**:sherpa-onnx + 流式 ONNX 模型(X-ASR / zipformer / Nemotron)—— 原生流式,每步成本恒定,CPU 约为前者的 1/35,中英准确率持平。
|
||||
|
||||
模型都放在 `~/.local/share/live-caption/models/<id>/`,注册表是 `data/models.json`
|
||||
(**加模型只加一条数据,不改代码**)。GUI 里可以直接下载(支持设置下载源与代理、断点续传、
|
||||
sha256 校验),命令行下也可以用 `scripts/fetch-models.sh`。
|
||||
|
||||
```bash
|
||||
# 流式后端
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model zipformer-zh-2025
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model nemotron35-560ms --language ja
|
||||
|
||||
# 辅助
|
||||
./build/live-caption-cli --list-devices # 列出可选采集设备
|
||||
./build/live-caption-cli --cli-live --device <sink> # 指定采集源
|
||||
./build/live-caption-cli --verify-model zipformer-zh-2025 # 校验模型完整性
|
||||
```
|
||||
|
||||
## 代码结构
|
||||
|
||||
```
|
||||
├─ src/ # 原型源码
|
||||
├─ docs/ # 各阶段验证报告
|
||||
└─ experiments/
|
||||
├─ phase0/ # 可行性验证脚本(采集/RTF/模型元数据)
|
||||
└─ phase1/ # 命令行原型说明与实机测试脚本
|
||||
src/core/ → liblivecaption_core(静态库,**不依赖 Qt**)
|
||||
iasr.h 推理后端抽象(便于用假实现测流式策略)
|
||||
transcript.{h,cpp} 输出解析、语言名映射
|
||||
audio.{h,cpp} monitor 采集 / 输出设备枚举 / WAV 读取 / 重采样
|
||||
qwen3asr.{h,cpp} 进程内推理(libllama + libmtmd)
|
||||
sherpaasr.{h,cpp} sherpa-onnx C API 适配(流式 ONNX)
|
||||
streamingasr.{h,cpp} 流式策略(切片复用 / 前缀回滚 / 原生流式分支)
|
||||
vad.h 能量 VAD
|
||||
livepipeline.{h,cpp} 实时管线:采集→VAD→分段→流式转写
|
||||
src/models/ → liblivecaption_models(静态库,Qt6::Core/Network)
|
||||
modelstore.{h,cpp} 注册表解析、安装检查、sha256 校验
|
||||
modeldownloader.{h,cpp} 应用内下载(镜像 / 代理 / 断点续传 / 进度)
|
||||
src/ui/ → liblivecaption_ui(静态库,Qt6::Widgets)
|
||||
captionwindow.{h,cpp} 悬浮字幕窗
|
||||
settingsdialog.{h,cpp} 设置对话框
|
||||
appsettings.{h,cpp} QSettings 配置
|
||||
livetranscriber.{h,cpp} LivePipeline 的 Qt 适配器(只转信号)
|
||||
apps/gui/ → live-caption (悬浮窗 + 托盘 + 设置)
|
||||
apps/cli/ → live-caption-cli (命令行程序,只链 Qt6::Core)
|
||||
apps/common/ 两个程序共用的命令行选项与后端工厂
|
||||
data/models.json 模型注册表(编译进二进制,加模型=加一条数据)
|
||||
data/live-caption.desktop / .svg 桌面入口与应用图标
|
||||
data/deb/ deb 的 postinst / postrm(刷新应用菜单与图标缓存)
|
||||
cmake/Packaging.cmake 安装规则与 CPack 配置(打 deb)
|
||||
tests/ 单元测试(QtTest,只链 core)
|
||||
scripts/fetch-models.sh 命令行下载模型(装到系统后叫 live-caption-fetch-models)
|
||||
experiments/ Phase 0/1 的验证脚本
|
||||
```
|
||||
|
||||
拆分的意义:**业务逻辑全在 core 且不依赖 Qt**,所以流式策略、VAD、输出解析这些最容易出错的部分可以脱离真模型和显示环境做单元测试;模型管理单独一层,GUI 与 CLI 各自独立演进,CLI 也不再需要链接 Qt Widgets。
|
||||
|
||||
## 打包成 deb
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
(cd build && cpack) # → build/live-caption_<版本>-<修订>_<架构>.deb
|
||||
sudo apt install ./build/live-caption_*.deb
|
||||
```
|
||||
|
||||
依赖由 `dpkg-shlibdeps` 从二进制自动推导;流式 ONNX 后端需要的 sherpa-onnx 运行时
|
||||
(发行版没有对应包)默认随包携带。细节与可调选项见 [docs/packaging.md](docs/packaging.md)。
|
||||
|
||||
## 文档
|
||||
|
||||
| 文档 | 内容 |
|
||||
|---|---|
|
||||
| [docs/gui.md](docs/gui.md) | 图形界面:首次配置、设置项说明、托盘、下载与校验 |
|
||||
| [docs/cli.md](docs/cli.md) | 全部命令行选项(含仅测试用的那些) |
|
||||
| [docs/asr-backends.md](docs/asr-backends.md) | 双后端结构、模型注册表、实测对比、语言推荐 |
|
||||
| [docs/packaging.md](docs/packaging.md) | 用 CPack 打 deb:包内容、依赖、RPATH、可调选项 |
|
||||
| [docs/troubleshooting.md](docs/troubleshooting.md) | 常见问题(窗口不见了、模型没下全、Wayland 置顶…) |
|
||||
| [docs/testing.md](docs/testing.md) | 测试分层、回归用例、GUI 交互测试钩子 |
|
||||
| [docs/phase0-verification.md](docs/phase0-verification.md) | Phase 0 可行性验证报告 |
|
||||
| [docs/phase2-streaming.md](docs/phase2-streaming.md) | Phase 2 流式解码 |
|
||||
| [docs/phase3-caption-window.md](docs/phase3-caption-window.md) | Phase 3 悬浮字幕窗 |
|
||||
@@ -0,0 +1,189 @@
|
||||
// 命令行版:转写文件、流式转写文件、或纯命令行实时字幕(不开窗口)。
|
||||
// 只依赖 core,不链接 Qt Widgets。
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <QCommandLineOption>
|
||||
#include <QCommandLineParser>
|
||||
|
||||
#include "appcli.h"
|
||||
#include "audio.h"
|
||||
#include "livepipeline.h"
|
||||
#include "iasr.h"
|
||||
#include "qwen3asr.h"
|
||||
#include "streamingasr.h"
|
||||
#include "transcript.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::atomic<bool> g_stop{false};
|
||||
|
||||
extern "C" void handleSigInt(int) { g_stop = true; }
|
||||
|
||||
int runFile(lc::IAsr & asr, const QString & path)
|
||||
{
|
||||
std::vector<float> pcm;
|
||||
std::string err;
|
||||
if (!lc::readWavMono(path.toStdString(), asr.sampleRate(), pcm, &err)) {
|
||||
std::fprintf(stderr, "读取音频失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
const double dur = (double) pcm.size() / asr.sampleRate();
|
||||
std::fprintf(stderr, "音频: %s (%.2fs)\n", qUtf8Printable(path), dur);
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
lc::AsrResult r = asr.transcribe(pcm.data(), pcm.size());
|
||||
const double wall = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
|
||||
if (!r.ok) {
|
||||
std::fprintf(stderr, "转写失败: %s\n", r.error.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::printf("语言: %s (%s)\n", r.transcript.language.c_str(),
|
||||
lc::languageDisplayName(r.transcript.language).c_str());
|
||||
std::printf("文本: %s\n", r.transcript.text.c_str());
|
||||
std::fprintf(stderr, "推理: %.2fs / 音频 %.2fs (rtf %.3f) 生成 %d tokens, 墙钟 %.2fs\n",
|
||||
r.inferSeconds, dur, dur > 0 ? r.inferSeconds / dur : 0, r.tokenCount, wall);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int runStreamFile(lc::IAsr & asr, const QString & path, const lc::StreamOptions & sop)
|
||||
{
|
||||
std::vector<float> pcm;
|
||||
std::string err;
|
||||
if (!lc::readWavMono(path.toStdString(), asr.sampleRate(), pcm, &err)) {
|
||||
std::fprintf(stderr, "读取音频失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
const double dur = (double) pcm.size() / asr.sampleRate();
|
||||
std::fprintf(stderr, "流式转写: %s (%.2fs) chunk=%.1fs segment=%.1fs mode=%s\n",
|
||||
qUtf8Printable(path), dur, sop.chunkSec, sop.maxUtteranceSec,
|
||||
sop.incremental ? "incremental" : "window");
|
||||
|
||||
lc::StreamingAsr stream(asr, sop);
|
||||
const size_t chunkSamples = (size_t) (sop.chunkSec * asr.sampleRate());
|
||||
|
||||
const auto onStep = [](const lc::StreamingAsr::Step & s) {
|
||||
std::printf("\n[chunk %2d] 累计 %5.1fs | 音频 %5.2fs | 前缀 %5.2fs | 生成 %5.2fs (%d tok) "
|
||||
"| 合计 %5.2fs%s\n",
|
||||
s.chunkIndex, s.windowSeconds, s.encodeSeconds, s.prefillSeconds,
|
||||
s.genSeconds, s.newTokens, s.inferSeconds,
|
||||
s.ok ? "" : " <失败>");
|
||||
if (!s.ok) std::printf(" error: %s\n", s.error.c_str());
|
||||
std::printf(" 已提交: %s\n", s.committed.c_str());
|
||||
std::fflush(stdout);
|
||||
};
|
||||
|
||||
for (size_t off = 0; off < pcm.size(); off += chunkSamples) {
|
||||
const size_t n = std::min(chunkSamples, pcm.size() - off);
|
||||
stream.feed(pcm.data() + off, n, onStep);
|
||||
}
|
||||
stream.flush(onStep);
|
||||
|
||||
std::printf("\n==== 最终提交文本 (%s) ====\n%s\n",
|
||||
lc::languageDisplayName(stream.language()).c_str(),
|
||||
stream.committedText().c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int runCliLive(lc::IAsr & asr, const lc::StreamOptions & sop, const QString & device)
|
||||
{
|
||||
lc::LivePipelineOptions popt;
|
||||
popt.stream = sop;
|
||||
|
||||
popt.captureDevice = device.toStdString();
|
||||
lc::LivePipeline pipeline(asr, popt);
|
||||
pipeline.setCaptionCallback([](const std::string & committed, const std::string & tail,
|
||||
const std::string & lang) {
|
||||
// 原地刷新:稳定部分正常显示,尾部用暗色表示未定
|
||||
std::printf("\r\033[K[%s] %s\033[2m%s\033[0m",
|
||||
lc::languageDisplayName(lang).c_str(), committed.c_str(), tail.c_str());
|
||||
std::fflush(stdout);
|
||||
});
|
||||
pipeline.setErrorCallback([](const std::string & m) {
|
||||
std::fprintf(stderr, "\n采集失败: %s\n", m.c_str());
|
||||
});
|
||||
|
||||
std::string err;
|
||||
if (!pipeline.start(&err)) {
|
||||
std::fprintf(stderr, "启动采集失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::fprintf(stderr, "正在采集: %s (Ctrl+C 退出)\n", pipeline.deviceName().c_str());
|
||||
std::signal(SIGINT, handleSigInt);
|
||||
while (!g_stop) std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
pipeline.stop();
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
QCoreApplication app(argc, argv);
|
||||
|
||||
QCommandLineParser parser;
|
||||
parser.setApplicationDescription(QStringLiteral("实时字幕(命令行版)"));
|
||||
parser.addHelpOption();
|
||||
lc::app::addModelOptions(parser);
|
||||
lc::app::addStreamOptions(parser);
|
||||
lc::app::addBackendOptions(parser);
|
||||
parser.addOption(QCommandLineOption("file", "转写一个 wav 文件后退出", "path"));
|
||||
parser.addOption(QCommandLineOption("stream-file", "以流式模式转写 wav 文件后退出", "path"));
|
||||
parser.addOption(QCommandLineOption("cli-live", "实时转写字幕,只用命令行输出(不开窗口)"));
|
||||
parser.addOption(QCommandLineOption("device", "采集源(sink 名);留空=跟随系统默认输出", "sink"));
|
||||
parser.addOption(QCommandLineOption("verify-model", "校验模型文件完整性后退出", "id"));
|
||||
parser.addOption(QCommandLineOption("list-devices", "列出可选的采集设备后退出"));
|
||||
parser.process(app);
|
||||
|
||||
const lc::AsrOptions asrOpt = lc::app::asrOptions(parser);
|
||||
lc::StreamOptions sop = lc::app::streamOptions(parser);
|
||||
|
||||
if (parser.isSet("list-devices")) {
|
||||
for (const auto & d : lc::listOutputDevices()) {
|
||||
std::printf(" %-60s %s%s\n", d.sink.c_str(), d.description.c_str(),
|
||||
d.isDefault ? " [默认]" : "");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (parser.isSet("verify-model")) {
|
||||
const auto * m = lc::models::ModelStore::find(parser.value("verify-model"));
|
||||
if (!m) { std::fprintf(stderr, "注册表里没有模型: %s\n", qUtf8Printable(parser.value("verify-model"))); return 1; }
|
||||
QStringList bad;
|
||||
const bool ok = lc::models::ModelStore::verify(*m, &bad, [](int done, int total) {
|
||||
std::fprintf(stderr, "\r校验中 %d/%d", done, total);
|
||||
});
|
||||
std::fprintf(stderr, "\n");
|
||||
if (ok) { std::printf("✅ %s 校验通过\n", qUtf8Printable(m->name)); return 0; }
|
||||
std::printf("❌ %s 校验失败,损坏: %s\n", qUtf8Printable(m->name),
|
||||
qUtf8Printable(bad.join(QStringLiteral(", "))));
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::string err;
|
||||
std::unique_ptr<lc::IAsr> asr = lc::app::makeAsr(parser, asrOpt, &err);
|
||||
if (!asr) {
|
||||
std::fprintf(stderr, "%s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
// 原生流式识别器很便宜,用更细的更新粒度换低延迟
|
||||
if (asr->kind() == lc::AsrKind::NativeStreaming && !parser.isSet("stream-chunk")) {
|
||||
sop.chunkSec = 0.32;
|
||||
}
|
||||
|
||||
if (parser.isSet("file")) return runFile(*asr, parser.value("file"));
|
||||
if (parser.isSet("stream-file")) return runStreamFile(*asr, parser.value("stream-file"), sop);
|
||||
|
||||
return runCliLive(*asr, sop, parser.value("device"));
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <QCommandLineOption>
|
||||
#include <QCommandLineParser>
|
||||
|
||||
#include "iasr.h"
|
||||
#include "modelstore.h"
|
||||
#include "streamingasr.h"
|
||||
#include "qwen3asr.h"
|
||||
#if defined(LC_HAVE_SHERPA)
|
||||
#include "sherpaasr.h"
|
||||
#endif
|
||||
|
||||
// 两个可执行程序(GUI / CLI)共用的命令行选项定义与解析。
|
||||
namespace lc::app {
|
||||
|
||||
// 构造命令行选项。
|
||||
//
|
||||
// Qt 自己不会把默认值印进 --help(构造函数里传的默认值只作为 value() 的兜底),
|
||||
// 所以这里在给了默认值时把「(默认 X)」拼到说明后面。
|
||||
inline QCommandLineOption makeOption(const QString & name, const QString & description,
|
||||
const QString & valueName = QString(),
|
||||
const QString & defaultValue = QString())
|
||||
{
|
||||
QString desc = description;
|
||||
if (!defaultValue.isEmpty()) {
|
||||
desc += QStringLiteral("(默认 %1)").arg(defaultValue);
|
||||
}
|
||||
if (valueName.isEmpty()) return QCommandLineOption(name, desc);
|
||||
return QCommandLineOption(name, desc, valueName, defaultValue);
|
||||
}
|
||||
|
||||
inline void addModelOptions(QCommandLineParser & p)
|
||||
{
|
||||
p.addOption(makeOption("model", "主模型 GGUF 路径(架构须为 qwen3vl)", "path"));
|
||||
p.addOption(makeOption("mmproj", "mmproj GGUF 路径(clip + qwen3a)", "path"));
|
||||
p.addOption(makeOption("threads", "推理线程数", "n", "8"));
|
||||
p.addOption(makeOption("max-tokens", "单段最多生成 token 数", "n", "256"));
|
||||
p.addOption(makeOption("verbose", "输出 llama.cpp/mtmd 的详细日志"));
|
||||
}
|
||||
|
||||
inline void addStreamOptions(QCommandLineParser & p)
|
||||
{
|
||||
p.addOption(makeOption("stream-chunk", "流式 chunk / 提交粒度,单位秒", "sec", "2.0"));
|
||||
p.addOption(makeOption("stream-window", "滑窗上限,单位秒;仅 window 模式,0=不滑窗", "sec", "16"));
|
||||
p.addOption(makeOption("stream-segment", "单段最长时长,单位秒;0=不限", "sec", "30"));
|
||||
p.addOption(makeOption("unfixed-tokens", "前缀回滚丢弃的 token 数", "n", "5"));
|
||||
p.addOption(makeOption("unfixed-chunks", "冷启动不带前缀的 chunk 数", "n", "2"));
|
||||
p.addOption(makeOption("stream-mode", "流式后端: incremental / append / window", "mode",
|
||||
"incremental"));
|
||||
}
|
||||
|
||||
inline AsrOptions asrOptions(const QCommandLineParser & p)
|
||||
{
|
||||
AsrOptions o;
|
||||
o.modelPath = p.value("model").toStdString();
|
||||
o.mmprojPath = p.value("mmproj").toStdString();
|
||||
o.threads = p.value("threads").toInt();
|
||||
o.maxTokens = p.value("max-tokens").toInt();
|
||||
o.verbose = p.isSet("verbose");
|
||||
return o;
|
||||
}
|
||||
|
||||
inline StreamOptions streamOptions(const QCommandLineParser & p)
|
||||
{
|
||||
StreamOptions o;
|
||||
o.chunkSec = p.value("stream-chunk").toDouble();
|
||||
o.windowSec = p.value("stream-window").toDouble();
|
||||
o.maxUtteranceSec = p.value("stream-segment").toDouble();
|
||||
o.unfixedTokenNum = p.value("unfixed-tokens").toInt();
|
||||
o.unfixedChunkNum = p.value("unfixed-chunks").toInt();
|
||||
o.maxTokensPerStep = p.value("max-tokens").toInt();
|
||||
o.incremental = p.value("stream-mode") == QLatin1String("incremental");
|
||||
o.appendOnly = p.value("stream-mode") == QLatin1String("append");
|
||||
return o;
|
||||
}
|
||||
|
||||
inline bool loadModel(Qwen3Asr & asr, const AsrOptions & opt)
|
||||
{
|
||||
if (opt.modelPath.empty() || opt.mmprojPath.empty()) {
|
||||
std::fprintf(stderr, "必须提供 --model 和 --mmproj\n");
|
||||
return false;
|
||||
}
|
||||
std::string err;
|
||||
if (!asr.load(opt, &err)) {
|
||||
std::fprintf(stderr, "加载失败: %s\n", err.c_str());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 推理后端选择 ----
|
||||
//
|
||||
// llama 后端:Qwen3-ASR 的 GGUF 模型(--model / --mmproj)
|
||||
// sherpa 后端:流式 ONNX 模型,按注册表 id 从模型存储目录取(--asr-model <id>)
|
||||
inline void addBackendOptions(QCommandLineParser & p)
|
||||
{
|
||||
p.addOption(makeOption("asr-backend", "推理后端: llama(Qwen3-ASR GGUF)或 sherpa(流式 ONNX)",
|
||||
"kind", "llama"));
|
||||
p.addOption(makeOption("asr-model", "模型注册表里的 id(sherpa 后端用它定位文件)", "id"));
|
||||
p.addOption(makeOption("model-dir", "覆盖模型存储目录(默认 ~/.local/share/live-caption/models)", "dir"));
|
||||
p.addOption(makeOption("language", "语言提示,多语言模型用(zh / en / ja …);留空=自动", "lang"));
|
||||
}
|
||||
|
||||
// 按注册表里的模型直接构造后端(GUI 用;不依赖任何命令行参数)
|
||||
inline std::unique_ptr<IAsr> makeAsrForModel(const models::ModelInfo & m,
|
||||
const QString & language,
|
||||
int threads, int maxTokens, bool verbose,
|
||||
std::string * err)
|
||||
{
|
||||
QStringList missing;
|
||||
if (!models::ModelStore::isInstalled(m, &missing)) {
|
||||
if (err) {
|
||||
*err = "模型未安装,缺失: " + missing.join(QStringLiteral(", ")).toStdString();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (m.backend == models::Backend::LlamaCpp) {
|
||||
AsrOptions o;
|
||||
o.modelPath = m.filePath(QStringLiteral("model")).toStdString();
|
||||
o.mmprojPath = m.filePath(QStringLiteral("mmproj")).toStdString();
|
||||
o.threads = threads;
|
||||
if (maxTokens > 0) o.maxTokens = maxTokens;
|
||||
o.verbose = verbose;
|
||||
auto a = std::make_unique<Qwen3Asr>();
|
||||
if (!a->load(o, err)) return nullptr;
|
||||
return a;
|
||||
}
|
||||
|
||||
#if defined(LC_HAVE_SHERPA)
|
||||
SherpaAsr::Options o;
|
||||
o.encoder = m.filePath(QStringLiteral("encoder")).toStdString();
|
||||
o.decoder = m.filePath(QStringLiteral("decoder")).toStdString();
|
||||
o.joiner = m.filePath(QStringLiteral("joiner")).toStdString();
|
||||
o.tokens = m.filePath(QStringLiteral("tokens")).toStdString();
|
||||
o.threads = 1; // 这类模型单线程最快
|
||||
if (m.languages.size() > 1 && !language.isEmpty()) o.language = language.toStdString();
|
||||
auto a = std::make_unique<SherpaAsr>();
|
||||
if (!a->load(o, err)) return nullptr;
|
||||
return a;
|
||||
#else
|
||||
if (err) *err = "编译时未找到 sherpa-onnx";
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 按命令行选择并加载后端;失败时返回 nullptr 并把原因写进 err
|
||||
inline std::unique_ptr<IAsr> makeAsr(const QCommandLineParser & p,
|
||||
const AsrOptions & asrOpt, std::string * err)
|
||||
{
|
||||
const QString dir = p.value("model-dir");
|
||||
if (!dir.isEmpty()) models::ModelStore::setRootOverride(dir);
|
||||
|
||||
const QString backend = p.value("asr-backend");
|
||||
const QString modelId = p.value("asr-model");
|
||||
const QString lang = p.value("language");
|
||||
|
||||
const models::ModelInfo * info =
|
||||
modelId.isEmpty() ? nullptr : models::ModelStore::find(modelId);
|
||||
if (!modelId.isEmpty() && !info) {
|
||||
if (err) *err = "注册表里没有模型: " + modelId.toStdString();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const bool useSherpa = (backend == QLatin1String("sherpa"))
|
||||
|| (info && info->backend == models::Backend::SherpaOnline);
|
||||
|
||||
if (useSherpa) {
|
||||
#if defined(LC_HAVE_SHERPA)
|
||||
if (!info) {
|
||||
if (err) *err = "sherpa 后端需要 --asr-model <id>(见 data/models.json)";
|
||||
return nullptr;
|
||||
}
|
||||
QStringList missing;
|
||||
if (!models::ModelStore::isInstalled(*info, &missing)) {
|
||||
if (err) {
|
||||
*err = "模型未安装,缺失: " + missing.join(QStringLiteral(", ")).toStdString()
|
||||
+ "\n 可运行: scripts/fetch-models.sh " + info->id.toStdString();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
SherpaAsr::Options o;
|
||||
o.encoder = info->filePath(QStringLiteral("encoder")).toStdString();
|
||||
o.decoder = info->filePath(QStringLiteral("decoder")).toStdString();
|
||||
o.joiner = info->filePath(QStringLiteral("joiner")).toStdString();
|
||||
o.tokens = info->filePath(QStringLiteral("tokens")).toStdString();
|
||||
o.threads = 1; // 这类模型单线程最快(多线程反而被同步开销拖慢)
|
||||
if (info->languages.size() > 1 && !lang.isEmpty()) {
|
||||
o.language = lang.toStdString(); // 多语言模型(Nemotron)需要语言提示
|
||||
}
|
||||
auto a = std::make_unique<SherpaAsr>();
|
||||
if (!a->load(o, err)) return nullptr;
|
||||
return a;
|
||||
#else
|
||||
if (err) *err = "编译时未找到 sherpa-onnx(-DSHERPA_ONNX_ROOT=...)";
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
auto a = std::make_unique<Qwen3Asr>();
|
||||
if (asrOpt.modelPath.empty() || asrOpt.mmprojPath.empty()) {
|
||||
if (err) *err = "llama 后端需要 --model 和 --mmproj(或改用 --asr-backend sherpa --asr-model <id>)";
|
||||
return nullptr;
|
||||
}
|
||||
if (!a->load(asrOpt, err)) return nullptr;
|
||||
return a;
|
||||
}
|
||||
|
||||
} // namespace lc::app
|
||||
@@ -0,0 +1,385 @@
|
||||
// 图形界面版:悬浮字幕窗 + 托盘 + 设置对话框。
|
||||
// 完全通过 GUI 使用;命令行参数保留,仅用于自动化测试(显式给出时覆盖设置)。
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
|
||||
#include <QAction>
|
||||
#include <QApplication>
|
||||
#include <QCommandLineOption>
|
||||
#include <QCommandLineParser>
|
||||
#include <QIcon>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QPainter>
|
||||
#include <QPixmap>
|
||||
#include <QPushButton>
|
||||
#include <QStringList>
|
||||
#include <QSystemTrayIcon>
|
||||
#include <QTabWidget>
|
||||
#include <QTimer>
|
||||
|
||||
#include "appcli.h"
|
||||
#include "appsettings.h"
|
||||
#include "captionwindow.h"
|
||||
#include "iasr.h"
|
||||
#include "livetranscriber.h"
|
||||
#include "modelstore.h"
|
||||
#include "qwen3asr.h"
|
||||
#include "settingsdialog.h"
|
||||
#include "streamingasr.h"
|
||||
#include "transcript.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// 托盘图标:直接画一个,免得依赖图标资源文件
|
||||
QIcon makeTrayIcon()
|
||||
{
|
||||
QPixmap pm(64, 64);
|
||||
pm.fill(Qt::transparent);
|
||||
QPainter p(&pm);
|
||||
p.setRenderHint(QPainter::Antialiasing);
|
||||
p.setBrush(QColor(20, 20, 20, 235));
|
||||
p.setPen(Qt::NoPen);
|
||||
p.drawRoundedRect(2, 12, 60, 40, 10, 10);
|
||||
p.setPen(QColor(240, 240, 240));
|
||||
QFont f = p.font();
|
||||
f.setPixelSize(26);
|
||||
f.setBold(true);
|
||||
p.setFont(f);
|
||||
p.drawText(pm.rect(), Qt::AlignCenter, QStringLiteral("字"));
|
||||
return QIcon(pm);
|
||||
}
|
||||
|
||||
// 把设置应用到字幕窗(字号/不透明度/行数/位置/灰色尾部)
|
||||
void applyAppearance(lc::CaptionWindow & window, const lc::AppSettings & cfg)
|
||||
{
|
||||
window.setPanelOpacity(cfg.opacityPercent);
|
||||
window.setTextFontSize(cfg.fontSize);
|
||||
window.setLineCounts(cfg.collapsedLines, cfg.expandedLines);
|
||||
window.setShowTail(cfg.showUnstableTail);
|
||||
if (cfg.hasWindowPos) window.move(cfg.windowPos);
|
||||
}
|
||||
|
||||
bool hasUsableModel()
|
||||
{
|
||||
using namespace lc::models;
|
||||
const lc::AppSettings & cfg = lc::AppSettings::instance();
|
||||
if (cfg.modelId.isEmpty()) return false;
|
||||
const ModelInfo * m = ModelStore::find(cfg.modelId);
|
||||
return m && ModelStore::isInstalled(*m);
|
||||
}
|
||||
|
||||
// 后端相关设置的「指纹」:这些值变了就必须重建后端(外观类改动不需要)。
|
||||
QString backendKeyOf(const lc::AppSettings & c)
|
||||
{
|
||||
return QStringList{ c.modelId,
|
||||
c.language,
|
||||
c.captureDevice,
|
||||
c.modelDir,
|
||||
c.streamMode,
|
||||
QString::number(c.chunkSec),
|
||||
QString::number(c.streamWindowSec),
|
||||
QString::number(c.streamSegmentSec),
|
||||
QString::number(c.unfixedTokens),
|
||||
QString::number(c.unfixedChunks),
|
||||
QString::number(c.maxTokens),
|
||||
QString::number(c.threads),
|
||||
QString::number(c.verbose ? 1 : 0) }
|
||||
.join(QLatin1Char('|'));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
|
||||
Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
|
||||
QApplication app(argc, argv);
|
||||
// 关键:本程序常驻托盘,"最后一个窗口关闭"不等于退出。
|
||||
// 否则首次启动时设置对话框一关(那时它是唯一窗口),Qt 就会把主事件循环也结束掉,
|
||||
// 表现为"点了确定程序就自己退出"。
|
||||
QApplication::setQuitOnLastWindowClosed(false);
|
||||
QCoreApplication::setApplicationName(QStringLiteral("live-caption"));
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("live-caption"));
|
||||
|
||||
lc::AppSettings & cfg = lc::AppSettings::instance();
|
||||
cfg.load();
|
||||
|
||||
// ---- 命令行(仅用于自动化测试,显式给出时覆盖设置)----
|
||||
QCommandLineParser parser;
|
||||
parser.setApplicationDescription(QStringLiteral("实时字幕(悬浮窗)"));
|
||||
parser.addHelpOption();
|
||||
lc::app::addModelOptions(parser);
|
||||
lc::app::addStreamOptions(parser);
|
||||
lc::app::addBackendOptions(parser);
|
||||
parser.addOption(QCommandLineOption("opacity", "背景不透明度(20-100)", "n"));
|
||||
parser.addOption(QCommandLineOption("screenshot", "启动后自动截图并退出", "path"));
|
||||
parser.addOption(QCommandLineOption("screenshot-delay", "截图前等待秒数", "sec", "6"));
|
||||
parser.addOption(QCommandLineOption("no-tray", "不创建托盘图标(测试用)"));
|
||||
parser.addOption(QCommandLineOption("screenshot-settings", "打开设置对话框截图后退出", "path"));
|
||||
parser.addOption(QCommandLineOption("settings-tab", "截图设置对话框时先切到某个页签(0-2 或 模型/显示/高级)", "tab"));
|
||||
parser.addOption(QCommandLineOption("settings-autoclose", "复现用:自动操作设置对话框(reject|close|accept|ok|apply)", "how"));
|
||||
parser.addOption(QCommandLineOption("quit-after", "运行若干秒后优雅退出(测试退出路径用)", "sec"));
|
||||
parser.process(app);
|
||||
|
||||
if (parser.isSet("asr-model")) cfg.modelId = parser.value("asr-model");
|
||||
if (parser.isSet("language")) cfg.language = parser.value("language");
|
||||
if (parser.isSet("opacity")) cfg.opacityPercent = parser.value("opacity").toInt();
|
||||
if (parser.isSet("model-dir")) cfg.modelDir = parser.value("model-dir");
|
||||
if (!cfg.modelDir.isEmpty()) lc::models::ModelStore::setRootOverride(cfg.modelDir);
|
||||
|
||||
// 仅用于验证渲染:打开设置对话框截图后退出
|
||||
if (parser.isSet("screenshot-settings")) {
|
||||
const QString path = parser.value("screenshot-settings");
|
||||
lc::SettingsDialog dlg(!hasUsableModel());
|
||||
// 可选:先切页签,便于给某个页单独截图
|
||||
const QString tab = parser.value("settings-tab");
|
||||
if (!tab.isEmpty()) {
|
||||
if (auto * tw = dlg.findChild<QTabWidget *>()) {
|
||||
bool numeric = false;
|
||||
const int n = tab.toInt(&numeric);
|
||||
if (numeric) {
|
||||
tw->setCurrentIndex(qBound(0, n, tw->count() - 1));
|
||||
} else {
|
||||
for (int i = 0; i < tw->count(); ++i) {
|
||||
if (tw->tabText(i) == tab) { tw->setCurrentIndex(i); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dlg.show();
|
||||
QTimer::singleShot(1200, &dlg, [&dlg, path] {
|
||||
dlg.grab().save(path);
|
||||
std::fprintf(stderr, "设置对话框截图: %s\n", qUtf8Printable(path));
|
||||
dlg.accept();
|
||||
});
|
||||
dlg.exec();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 复现用:把"点 ✕ / 点确定"自动化,用来定位崩溃
|
||||
const QString autoclose = parser.value("settings-autoclose");
|
||||
const auto scheduleAutoclose = [&autoclose](QDialog & dlg) {
|
||||
if (autoclose.isEmpty()) return;
|
||||
QTimer::singleShot(700, &dlg, [&dlg, &autoclose] {
|
||||
if (autoclose == QLatin1String("reject")) dlg.reject();
|
||||
else if (autoclose == QLatin1String("close")) dlg.close(); // 标题栏 ✕
|
||||
else if (autoclose == QLatin1String("accept")) dlg.accept();
|
||||
else if (autoclose == QLatin1String("ok")) { // 真的点「确定」
|
||||
for (auto * b : dlg.findChildren<QPushButton *>()) {
|
||||
if (b->text() == QObject::tr("确定")) { b->click(); break; }
|
||||
}
|
||||
}
|
||||
else if (autoclose == QLatin1String("apply")) { // 点「应用」,应保持打开
|
||||
for (auto * b : dlg.findChildren<QPushButton *>()) {
|
||||
if (b->text() == QObject::tr("应用")) { b->click(); break; }
|
||||
}
|
||||
QTimer::singleShot(400, &dlg, [&dlg] {
|
||||
std::fprintf(stderr, "点「应用」后对话框仍可见: %s\n",
|
||||
dlg.isVisible() ? "是 ✅" : "否 ❌");
|
||||
dlg.reject();
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// ---- 启动:没有可用模型就先开设置 ----
|
||||
if (!hasUsableModel()) {
|
||||
lc::SettingsDialog dlg(true);
|
||||
scheduleAutoclose(dlg);
|
||||
if (dlg.exec() != QDialog::Accepted || !hasUsableModel()) return 0;
|
||||
}
|
||||
|
||||
lc::CaptionWindow window;
|
||||
applyAppearance(window, cfg);
|
||||
// 语言 pill:流式模型不提供语言识别,就显示设置里选的语言
|
||||
if (!cfg.language.isEmpty()) {
|
||||
window.setLanguage(
|
||||
QString::fromStdString(lc::languageDisplayNameFromCode(cfg.language.toStdString())));
|
||||
}
|
||||
|
||||
// 注意声明顺序:asr 必须在 live 之前声明,
|
||||
// 这样析构时 live(会 join 工作线程)先销毁、asr 后销毁,避免 use-after-free。
|
||||
std::unique_ptr<lc::IAsr> asr;
|
||||
lc::LiveTranscriber live; // 后端在 startTranscriber() 里注入
|
||||
const auto startTranscriber = [&]() -> bool {
|
||||
live.stop();
|
||||
asr.reset();
|
||||
live.setCaptureDevice(cfg.captureDevice);
|
||||
|
||||
const lc::models::ModelInfo * m = lc::models::ModelStore::find(cfg.modelId);
|
||||
if (!m) {
|
||||
qCritical("找不到模型 %s", qUtf8Printable(cfg.modelId));
|
||||
return false;
|
||||
}
|
||||
std::string err;
|
||||
asr = lc::app::makeAsrForModel(*m, cfg.language, cfg.threads, cfg.maxTokens,
|
||||
cfg.verbose || parser.isSet("verbose"), &err);
|
||||
if (!asr) {
|
||||
qCritical("加载模型失败: %s", err.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 流式参数:只有 llama 后端(Qwen3-ASR)用得到大部分参数,
|
||||
// 流式 ONNX 只关心「更新粒度」。
|
||||
lc::StreamOptions sop;
|
||||
sop.windowSec = cfg.streamWindowSec;
|
||||
sop.maxUtteranceSec = cfg.streamSegmentSec;
|
||||
sop.unfixedTokenNum = cfg.unfixedTokens;
|
||||
sop.unfixedChunkNum = cfg.unfixedChunks;
|
||||
sop.maxTokensPerStep = cfg.maxTokens;
|
||||
sop.incremental = (cfg.streamMode != QLatin1String("append")
|
||||
&& cfg.streamMode != QLatin1String("window"));
|
||||
sop.appendOnly = (cfg.streamMode == QLatin1String("append"));
|
||||
if (asr->kind() == lc::AsrKind::NativeStreaming) {
|
||||
sop.chunkSec = (cfg.chunkSec > 0.0) ? cfg.chunkSec : 0.32;
|
||||
} else if (cfg.chunkSec > 0.0) {
|
||||
sop.chunkSec = cfg.chunkSec;
|
||||
}
|
||||
QString qerr;
|
||||
if (!live.start(*asr, sop, &qerr)) {
|
||||
qCritical("启动采集失败: %s", qUtf8Printable(qerr));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
QObject::connect(&live, &lc::LiveTranscriber::caption, &window,
|
||||
[&window](const QString & committed, const QString & tail,
|
||||
const QString & lang) {
|
||||
if (!lang.isEmpty()) {
|
||||
window.setLanguage(
|
||||
QString::fromStdString(lc::languageDisplayName(lang.toStdString())));
|
||||
}
|
||||
window.setCaption(committed, tail);
|
||||
});
|
||||
QObject::connect(&live, &lc::LiveTranscriber::failed, &window, [](const QString & m) {
|
||||
qWarning("采集失败: %s", qUtf8Printable(m));
|
||||
});
|
||||
|
||||
// 后端相关项(模型/语言/采集设备/流式参数)变化才需要重启;外观类改动即时生效
|
||||
QString activeKey = backendKeyOf(cfg);
|
||||
|
||||
const auto openSettings = [&] {
|
||||
// 后端相关项变化时:先把语言标签跟设置对齐(流式模型没有自动检测结果来更新它),
|
||||
// 再重启识别后端。
|
||||
const auto applyBackend = [&]() -> bool {
|
||||
if (backendKeyOf(cfg) == activeKey) return true;
|
||||
window.setLanguage(cfg.language.isEmpty()
|
||||
? QString()
|
||||
: QString::fromStdString(
|
||||
lc::languageDisplayNameFromCode(cfg.language.toStdString())));
|
||||
if (!startTranscriber()) return false;
|
||||
activeKey = backendKeyOf(cfg);
|
||||
return true;
|
||||
};
|
||||
|
||||
lc::SettingsDialog dlg(false);
|
||||
QObject::connect(&dlg, &lc::SettingsDialog::settingsApplied, &window, [&] {
|
||||
lc::models::ModelStore::setRootOverride(cfg.modelDir);
|
||||
applyAppearance(window, cfg); // 透明度/字号等立刻可见
|
||||
applyBackend();
|
||||
});
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
lc::models::ModelStore::setRootOverride(cfg.modelDir);
|
||||
applyAppearance(window, cfg);
|
||||
if (!applyBackend()) {
|
||||
QMessageBox::warning(&window, QObject::tr("启动失败"),
|
||||
QObject::tr("模型加载失败,请检查设置。"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 语言 pill → 设置
|
||||
QObject::connect(&window, &lc::CaptionWindow::languageClicked, &window, openSettings);
|
||||
|
||||
// ---- 托盘 ----
|
||||
QSystemTrayIcon * tray = nullptr;
|
||||
QMenu * trayMenu = nullptr;
|
||||
if (!parser.isSet("no-tray")) {
|
||||
tray = new QSystemTrayIcon(makeTrayIcon(), &app);
|
||||
tray->setToolTip(QObject::tr("实时字幕"));
|
||||
trayMenu = new QMenu(&window); // 必须有归属,否则退出时是悬空顶层窗口
|
||||
auto * showAct = trayMenu->addAction(QObject::tr("显示/隐藏字幕"));
|
||||
auto * setAct = trayMenu->addAction(QObject::tr("设置…"));
|
||||
trayMenu->addSeparator();
|
||||
auto * quitAct = trayMenu->addAction(QObject::tr("退出"));
|
||||
tray->setContextMenu(trayMenu);
|
||||
|
||||
QObject::connect(showAct, &QAction::triggered, &window,
|
||||
[&window] { window.setVisible(!window.isVisible()); });
|
||||
QObject::connect(setAct, &QAction::triggered, &window, openSettings);
|
||||
QObject::connect(quitAct, &QAction::triggered, &app, &QApplication::quit);
|
||||
QObject::connect(tray, &QSystemTrayIcon::activated, &window,
|
||||
[&window](QSystemTrayIcon::ActivationReason r) {
|
||||
if (r == QSystemTrayIcon::Trigger) {
|
||||
window.setVisible(!window.isVisible());
|
||||
}
|
||||
});
|
||||
tray->show();
|
||||
}
|
||||
|
||||
// 关闭按钮 = 隐藏到托盘(否则关掉就没法再打开了)
|
||||
QObject::connect(&window, &lc::CaptionWindow::closed, &window, [&] {
|
||||
if (tray) {
|
||||
window.hide();
|
||||
} else {
|
||||
qApp->quit();
|
||||
}
|
||||
});
|
||||
|
||||
// 记住拖动后的位置
|
||||
QObject::connect(&window, &lc::CaptionWindow::moved, &window, [&](const QPoint & p) {
|
||||
cfg.windowPos = p;
|
||||
cfg.hasWindowPos = true;
|
||||
cfg.save();
|
||||
});
|
||||
|
||||
if (!startTranscriber()) {
|
||||
QMessageBox::critical(nullptr, QObject::tr("启动失败"),
|
||||
QObject::tr("无法加载模型,请检查设置。"));
|
||||
return 1;
|
||||
}
|
||||
|
||||
window.show();
|
||||
|
||||
// 复现用:程序起来后再开一次设置并自动关闭(模拟从语言标签/托盘进设置)
|
||||
if (!autoclose.isEmpty() && hasUsableModel()) {
|
||||
QTimer::singleShot(2500, &window, [&] {
|
||||
lc::SettingsDialog dlg(false);
|
||||
scheduleAutoclose(dlg);
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
applyAppearance(window, cfg);
|
||||
if (!startTranscriber()) qWarning("重启转写失败");
|
||||
}
|
||||
QTimer::singleShot(500, qApp, &QCoreApplication::quit);
|
||||
});
|
||||
}
|
||||
|
||||
// 自截图(验证渲染用)
|
||||
if (parser.isSet("screenshot")) {
|
||||
const QString path = parser.value("screenshot");
|
||||
QTimer::singleShot(parser.value("screenshot-delay").toInt() * 1000, &window,
|
||||
[&window, path] {
|
||||
const bool ok1 = window.grab().save(path);
|
||||
window.setCollapsed(false);
|
||||
QString expanded = path;
|
||||
expanded.replace(QStringLiteral(".png"), QStringLiteral("-expanded.png"));
|
||||
const bool ok2 = window.grab().save(expanded);
|
||||
std::fprintf(stderr, "截图: 折叠态 %s / 展开态 %s\n",
|
||||
ok1 ? "成功" : "失败", ok2 ? "成功" : "失败");
|
||||
QCoreApplication::quit();
|
||||
});
|
||||
}
|
||||
|
||||
if (parser.isSet("quit-after")) {
|
||||
QTimer::singleShot(parser.value("quit-after").toInt() * 1000, qApp,
|
||||
&QCoreApplication::quit);
|
||||
}
|
||||
|
||||
const int rc = QCoreApplication::exec();
|
||||
// 显式收尾,确保工作线程停下来之后再释放后端
|
||||
live.stop();
|
||||
asr.reset();
|
||||
return rc;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安装规则与打包(CPack → .deb)
|
||||
#
|
||||
# cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
# cmake --build build -j
|
||||
# cpack --config build/CPackConfig.cmake # 产 deb
|
||||
# cpack --config build/CPackConfig.cmake -G DEB # 只产 deb 更明确
|
||||
#
|
||||
# 产物:build/live-caption_<版本>-<修订>_<架构>.deb
|
||||
# dpkg -c <deb> # 看文件清单
|
||||
# dpkg -I <deb> # 看控制信息 / 依赖
|
||||
# sudo apt install ./<deb>
|
||||
#
|
||||
# 说明与取舍见 docs/packaging.md。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
option(LC_INSTALL "生成安装与打包规则" ON)
|
||||
option(LC_BUNDLE_SHERPA "把 sherpa-onnx 运行时打进包里(流式后端依赖它,而发行版没有对应包)" ON)
|
||||
option(LC_PACKAGE_STRIP "打包时 strip 二进制(发布建议打开;要用 coredump 调试符号就关掉)" OFF)
|
||||
|
||||
if(NOT LC_INSTALL)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# 包私有库目录。Debian 允许包把自己的私有共享库放在 /usr/lib/<包名>/,
|
||||
# 这样不必占用 multiarch 目录,也避免和系统库撞名。
|
||||
# 顶层 CMakeLists.txt 里已经定义(RPATH 要用),这里只是兜底。
|
||||
if(NOT DEFINED LC_PRIVATE_LIBDIR)
|
||||
set(LC_PRIVATE_LIBDIR "lib/live-caption")
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安装规则
|
||||
# ---------------------------------------------------------------------------
|
||||
install(TARGETS live-caption live-caption-cli
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
# 桌面入口与图标(GUI 才会出现在应用菜单里;CLI 无入口)
|
||||
install(FILES data/live-caption.desktop
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
|
||||
install(FILES data/live-caption.svg
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps)
|
||||
|
||||
# 模型注册表与下载脚本。注意:程序自己也把注册表编进了二进制(qt_add_resources),
|
||||
# 这里装一份是为了让脚本在没有程序的情况下也能用。
|
||||
install(FILES data/models.json
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/live-caption)
|
||||
install(PROGRAMS scripts/fetch-models.sh
|
||||
DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
RENAME live-caption-fetch-models)
|
||||
|
||||
# sherpa-onnx 运行时:官方只发预编译 tar 包,没有系统包可依赖,
|
||||
# 所以默认随包携带(约 32MB)。关掉的话流式 ONNX 后端在安装后的机器上会起不来。
|
||||
if(LC_HAS_SHERPA AND LC_BUNDLE_SHERPA)
|
||||
install(FILES ${LC_SHERPA_C_API} ${LC_SHERPA_ORT}
|
||||
DESTINATION ${LC_PRIVATE_LIBDIR})
|
||||
message(STATUS "打包: sherpa-onnx 运行时会随包安装到 /usr/${LC_PRIVATE_LIBDIR}")
|
||||
endif()
|
||||
|
||||
# 文档
|
||||
install(FILES README.md DESTINATION ${CMAKE_INSTALL_DOCDIR})
|
||||
install(FILES docs/gui.md docs/cli.md docs/asr-backends.md docs/troubleshooting.md
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/docs)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CPack
|
||||
# ---------------------------------------------------------------------------
|
||||
set(CPACK_GENERATOR "DEB")
|
||||
set(CPACK_PACKAGE_NAME "live-caption")
|
||||
set(CPACK_PACKAGE_VENDOR "live-caption")
|
||||
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY
|
||||
"系统播放音频的实时字幕(类似 Chrome 实时字幕)")
|
||||
set(CPACK_PACKAGE_INSTALL_DIRECTORY "live-caption")
|
||||
set(CPACK_PACKAGING_INSTALL_PREFIX "/usr")
|
||||
set(CPACK_STRIP_FILES ${LC_PACKAGE_STRIP})
|
||||
|
||||
# 维护者信息:发布前用 -DLC_DEB_MAINTAINER="名字 <邮箱>" 覆盖(Debian 要求可联系到人)
|
||||
set(LC_DEB_MAINTAINER "live-caption maintainers <live-caption@example.com>"
|
||||
CACHE STRING "Debian Maintainer 字段")
|
||||
set(LC_DEB_HOMEPAGE "" CACHE STRING "Debian Homepage 字段(留空则不写)")
|
||||
set(CPACK_PACKAGE_CONTACT "${LC_DEB_MAINTAINER}")
|
||||
|
||||
# Debian 控制字段
|
||||
set(CPACK_DEBIAN_PACKAGE_NAME "live-caption")
|
||||
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "${LC_DEB_MAINTAINER}")
|
||||
set(CPACK_DEBIAN_PACKAGE_SECTION "utils")
|
||||
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
|
||||
set(CPACK_DEBIAN_PACKAGE_RELEASE "1") # Debian 修订号
|
||||
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") # live-caption_0.1.0-1_amd64.deb
|
||||
if(NOT LC_DEB_HOMEPAGE STREQUAL "")
|
||||
set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "${LC_DEB_HOMEPAGE}")
|
||||
endif()
|
||||
|
||||
# 维护者脚本:刷新应用菜单与图标缓存(见 data/deb/)
|
||||
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/data/deb/postinst;${CMAKE_CURRENT_SOURCE_DIR}/data/deb/postrm")
|
||||
|
||||
# 依赖由 dpkg-shlibdeps 从二进制里推出来(libllama0 / libpulse0 / libsamplerate0 /
|
||||
# Qt6 各库…),比手写列表可靠。包内自带的 sherpa 库(RPATH 指向 $ORIGIN/../lib/
|
||||
# live-caption)会被识别为私有库,不会变成外部依赖。
|
||||
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
|
||||
# 需要手动补依赖时,用 -DLC_DEB_EXTRA_DEPENDS=... 追加(逗号分隔;给了就覆盖自动结果)
|
||||
set(LC_DEB_EXTRA_DEPENDS "" CACHE STRING "额外写入 Depends 的包(逗号分隔)")
|
||||
if(NOT LC_DEB_EXTRA_DEPENDS STREQUAL "")
|
||||
set(CPACK_DEBIAN_PACKAGE_DEPENDS "${LC_DEB_EXTRA_DEPENDS}")
|
||||
endif()
|
||||
|
||||
set(CPACK_DEBIAN_PACKAGE_DESCRIPTION
|
||||
"实时字幕:采集系统播放声音的输出(monitor),把语音实时转写成字幕并叠加显示。
|
||||
.
|
||||
两条推理后端:llama.cpp(Qwen3-ASR 的 GGUF 模型,准确率高、语言最全)与
|
||||
sherpa-onnx(流式 ONNX 模型,原生流式、CPU 占用低)。模型不随包分发,
|
||||
首次启动时在设置界面里按需下载(支持镜像与代理断点续传)。")
|
||||
|
||||
include(CPack)
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# 安装后刷新桌面数据库与图标缓存,否则刚装完的应用菜单里可能看不到这个条目。
|
||||
# (本包的共享库在 /usr/lib/live-caption/,靠二进制的 RPATH 查找,不走 ldconfig,
|
||||
# 这里仍然调一下只是兜底。)
|
||||
set -e
|
||||
|
||||
case "$1" in
|
||||
configure)
|
||||
ldconfig
|
||||
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
update-desktop-database -q /usr/share/applications || true
|
||||
fi
|
||||
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
||||
gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
# 卸载后同样刷新缓存,避免菜单里留下一个指向已删除程序的条目。
|
||||
set -e
|
||||
|
||||
case "$1" in
|
||||
remove|purge)
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
update-desktop-database -q /usr/share/applications || true
|
||||
fi
|
||||
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
||||
gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,17 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Version=1.0
|
||||
Name=Live Caption
|
||||
Name[zh_CN]=实时字幕
|
||||
GenericName=Real-time captions
|
||||
GenericName[zh_CN]=实时字幕
|
||||
Comment=Show live subtitles for the audio your system is playing
|
||||
Comment[zh_CN]=把系统正在播放的声音实时转写成字幕
|
||||
Exec=live-caption
|
||||
TryExec=live-caption
|
||||
Icon=live-caption
|
||||
Terminal=false
|
||||
Categories=AudioVideo;Audio;
|
||||
Keywords=caption;subtitle;subtitles;speech;transcription;asr;
|
||||
Keywords[zh_CN]=字幕;实时字幕;语音识别;听写;
|
||||
StartupNotify=false
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
live-caption 图标。
|
||||
|
||||
刻意不用文字(字形)而画成「字幕面板」:SVG 里的 <text> 依赖渲染环境有对应字体,
|
||||
而这条图标要跟着主题一起渲染。所以画成和悬浮窗一样的样子 ——
|
||||
深色圆角面板 + 一行已稳定文本(白)+ 一行不稳定尾部(灰)。
|
||||
-->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<clipPath id="panel">
|
||||
<rect x="2" y="11" width="60" height="42" rx="10"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<!-- 面板 -->
|
||||
<rect x="2" y="11" width="60" height="42" rx="10" fill="#1b1b1b"/>
|
||||
<rect x="2" y="11" width="60" height="42" rx="10" fill="none"
|
||||
stroke="#3a3a3a" stroke-width="1.5"/>
|
||||
|
||||
<!-- 已稳定文本 -->
|
||||
<g clip-path="url(#panel)">
|
||||
<rect x="11" y="24" width="42" height="6" rx="3" fill="#f5f5f5"/>
|
||||
<!-- 不稳定尾部 -->
|
||||
<rect x="11" y="35" width="26" height="6" rx="3" fill="#8d8d8d"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1016 B |
@@ -0,0 +1,168 @@
|
||||
{
|
||||
"version": 1,
|
||||
"comment": "live-caption 的模型注册表。新增模型 = 在这里加一条,不需要改代码。",
|
||||
"models": [
|
||||
{
|
||||
"id": "qwen3-asr-0.6b-q8",
|
||||
"name": "Qwen3-ASR 0.6B(通用,52 语言)",
|
||||
"backend": "llama-cpp",
|
||||
"languages": [
|
||||
"zh",
|
||||
"en",
|
||||
"ja",
|
||||
"ko",
|
||||
"fr",
|
||||
"de",
|
||||
"es",
|
||||
"ru",
|
||||
"ar",
|
||||
"auto"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"note": "973MB,准确率高、语言最全、自带语言识别;但每步成本随句子增长(CPU 约为流式后端的 35 倍)",
|
||||
"files": {
|
||||
"model": {
|
||||
"name": "Qwen3-ASR-0.6B-Q8_0.gguf",
|
||||
"url": "https://hf-mirror.com/ggml-org/Qwen3-ASR-0.6B-GGUF/resolve/main/Qwen3-ASR-0.6B-Q8_0.gguf",
|
||||
"size": 804749248,
|
||||
"sha256": "bca259818b50ca7c4c05e9bdb35a5dc04fa039653a6d6f3f0f331f96f6aa1971"
|
||||
},
|
||||
"mmproj": {
|
||||
"name": "mmproj-Qwen3-ASR-0.6B-Q8_0.gguf",
|
||||
"url": "https://hf-mirror.com/ggml-org/Qwen3-ASR-0.6B-GGUF/resolve/main/mmproj-Qwen3-ASR-0.6B-Q8_0.gguf",
|
||||
"size": 214392480,
|
||||
"sha256": "41a342b5e4c514e968cb756de6cd1b7be39eff43c44c57a2ef5fc6522e36603d"
|
||||
}
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": "zipformer-zh-2025",
|
||||
"name": "中文流式(k2-fsa 官方 2025-06-30)",
|
||||
"backend": "sherpa-online",
|
||||
"languages": [
|
||||
"zh"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"note": "154MB,实测中文逐字正确;首个字幕 0.48s,约 0.10 核·秒/秒音频",
|
||||
"files": {
|
||||
"encoder": {
|
||||
"name": "encoder.int8.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30/resolve/main/encoder.int8.onnx",
|
||||
"size": 161141793,
|
||||
"sha256": "5ac51e27981bb4dab01bb9be4958453ba50c3b61c063ddda0eab23fd3671aa4f"
|
||||
},
|
||||
"decoder": {
|
||||
"name": "decoder.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30/resolve/main/decoder.onnx",
|
||||
"size": 5165083,
|
||||
"sha256": "06522ad63cec0fdf6809f4e1db9bb4f7d710c34582e3b35db62ac60eccafac7e"
|
||||
},
|
||||
"joiner": {
|
||||
"name": "joiner.int8.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30/resolve/main/joiner.int8.onnx",
|
||||
"size": 1033416,
|
||||
"sha256": "b34584dc6f561089e1d747fedebb3765f2caa72c927ef54d7ca55e5ae40a814b"
|
||||
},
|
||||
"tokens": {
|
||||
"name": "tokens.txt",
|
||||
"url": "https://hf-mirror.com/csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30/resolve/main/tokens.txt",
|
||||
"size": 20628,
|
||||
"sha256": "6193c7ea1c96d0d9a1e9652789b40d13a8a913b434a5451e93158f5a09fd6652"
|
||||
}
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": "xasr-zh-en-480",
|
||||
"name": "中英流式(X-ASR-zh-en, 480ms)",
|
||||
"backend": "sherpa-online",
|
||||
"languages": [
|
||||
"zh",
|
||||
"en"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"note": "587MB,实测中英准确率与 Qwen3-ASR 持平;首个字幕 1.44s",
|
||||
"files": {
|
||||
"encoder": {
|
||||
"name": "encoder-480ms.onnx",
|
||||
"url": "https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/main/deployment/models/chunk-480ms-model/encoder-480ms.onnx",
|
||||
"size": 592968361,
|
||||
"sha256": "0c3454033d249081df124ddcd7adaf3deca07d0b999b26f2ee5d2475d37abc74"
|
||||
},
|
||||
"decoder": {
|
||||
"name": "decoder-480ms.onnx",
|
||||
"url": "https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/main/deployment/models/chunk-480ms-model/decoder-480ms.onnx",
|
||||
"size": 11309084,
|
||||
"sha256": "3658368d274a5d5fd39a7ac20c46bed0ad9cfea1f0feddef30d5d89797c1f499"
|
||||
},
|
||||
"joiner": {
|
||||
"name": "joiner-480ms.onnx",
|
||||
"url": "https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/main/deployment/models/chunk-480ms-model/joiner-480ms.onnx",
|
||||
"size": 10260467,
|
||||
"sha256": "03781c98165a2385024c9cecdd2b6b13310d81db23a62c7da420782c2915cf81"
|
||||
},
|
||||
"tokens": {
|
||||
"name": "tokens.txt",
|
||||
"url": "https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/main/deployment/models/chunk-480ms-model/tokens.txt",
|
||||
"size": 58806,
|
||||
"sha256": "b818a60878b9aae978cbb8ad594acbd403d76d1af2e31ef4197c84e2dbdba27c"
|
||||
}
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": "nemotron35-560ms",
|
||||
"name": "多语言流式(Nemotron 3.5, 560ms, 含日语)",
|
||||
"backend": "sherpa-online",
|
||||
"languages": [
|
||||
"en",
|
||||
"ja",
|
||||
"ko",
|
||||
"vi",
|
||||
"ru",
|
||||
"ar",
|
||||
"hi",
|
||||
"fr",
|
||||
"de",
|
||||
"es",
|
||||
"it",
|
||||
"pt",
|
||||
"nl",
|
||||
"tr",
|
||||
"uk",
|
||||
"zh"
|
||||
],
|
||||
"license": "OpenMDW-1.1",
|
||||
"note": "651MB,40 种语言 + 内置语言识别;实测中英日都可用但都有瑕疵",
|
||||
"optionsHint": "language",
|
||||
"files": {
|
||||
"encoder": {
|
||||
"name": "encoder.int8.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11/resolve/main/encoder.int8.onnx",
|
||||
"size": 657601403,
|
||||
"sha256": "012e9321373af99021415e0b0eb3ec827b4be3153be6f30d9b448fe65e896e68"
|
||||
},
|
||||
"decoder": {
|
||||
"name": "decoder.int8.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11/resolve/main/decoder.int8.onnx",
|
||||
"size": 14978075,
|
||||
"sha256": "19f9c98fc6d0a2c33a65a43b36fdb2e914c26c0aa9764be3aebc502a1e982fb0"
|
||||
},
|
||||
"joiner": {
|
||||
"name": "joiner.int8.onnx",
|
||||
"url": "https://hf-mirror.com/csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11/resolve/main/joiner.int8.onnx",
|
||||
"size": 9504438,
|
||||
"sha256": "4101c7c679a0bc30483794b27a059e34e79232aa2068d78d51231a22c8b0d7ce"
|
||||
},
|
||||
"tokens": {
|
||||
"name": "tokens.txt",
|
||||
"url": "https://hf-mirror.com/csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11/resolve/main/tokens.txt",
|
||||
"size": 131440,
|
||||
"sha256": "729cc103155bafa785f9cd45746cd41cabe97eab7182fc04d594129587958f8a"
|
||||
}
|
||||
},
|
||||
"options": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
# 推理后端与模型管理
|
||||
|
||||
## 结构:2 个实现覆盖所有模型
|
||||
|
||||
实测确认了一件很重要的事:**不同模型不需要各写一套代码**。所有流式 ONNX 模型走的是同一套 API,差别只是「指向哪个模型文件 + 几行选项」。
|
||||
|
||||
```
|
||||
IAsr(src/core/iasr.h)
|
||||
├─ Qwen3Asr llama.cpp / ggml GGUF 模型(Qwen3-ASR) AsrKind::PrefixRollback
|
||||
└─ SherpaAsr sherpa-onnx / onnxruntime
|
||||
├─ X-ASR-zh-en 中英流式
|
||||
├─ zipformer-zh-2025 中文流式(k2-fsa 官方)
|
||||
└─ Nemotron-3.5 40 语言流式(含日语) AsrKind::NativeStreaming
|
||||
```
|
||||
|
||||
两条路径的区别(`StreamingAsr` 里按 `IAsr::kind()` 分流):
|
||||
|
||||
| | PrefixRollback | NativeStreaming |
|
||||
|---|---|---|
|
||||
| 模型类型 | 离线模型(LLM 解码器) | 有状态流式识别器 |
|
||||
| 上层要做的 | 切块 + 前缀回滚 + KV 复用 | 只喂音频,取当前整句文本 |
|
||||
| 每步成本 | 随句子长度增长 | 恒定 |
|
||||
| 已稳定/不稳定 | 用 token 回滚算 | 用「与上次的公共前缀」算 |
|
||||
|
||||
## 模型注册表与存储
|
||||
|
||||
**新增模型 = 加一条数据,不改代码。**
|
||||
|
||||
- 注册表:`data/models.json`(编译进二进制,同时也给脚本用)
|
||||
- 存储位置:`~/.local/share/live-caption/models/<id>/`
|
||||
(即 `QStandardPaths::GenericDataLocation + /live-caption/models`)
|
||||
- 下载:GUI 的「模型 → 下载」,或 `scripts/fetch-models.sh [id...]` / `--all`;已存在的文件会跳过
|
||||
|
||||
```bash
|
||||
./scripts/fetch-models.sh # 列出模型与安装状态
|
||||
./scripts/fetch-models.sh zipformer-zh-2025
|
||||
```
|
||||
|
||||
一条模型长这样:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "zipformer-zh-2025",
|
||||
"name": "中文流式(k2-fsa 官方 2025-06-30)",
|
||||
"backend": "sherpa-online", // llama-cpp | sherpa-online
|
||||
"languages": ["zh"],
|
||||
"license": "Apache-2.0",
|
||||
"note": "167MB,最快最准的中文流式模型",
|
||||
"files": {
|
||||
"encoder": { "name": "encoder.int8.onnx", "url": "https://...", "size": 161000000, "sha256": "5ac5..." },
|
||||
"tokens": { "name": "tokens.txt", "url": "https://...", "size": 3000, "sha256": "6193..." }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`size` / `sha256` 就是完整性校验的依据:**打开/选择模型时只比大小**(快),
|
||||
「校验完整性」或 `--verify-model` 才**重算 sha256**(慢,但能发现内容损坏)。
|
||||
|
||||
## 模型清单
|
||||
|
||||
| id | 语言 | 后端 | 许可 | 体积 | sha256(首个文件,前 16 位) |
|
||||
|---|---|---|---|---|---|
|
||||
| `qwen3-asr-0.6b-q8` | 52 语言 | llama-cpp | Apache-2.0 | 1019MB | `bca259818b50ca7c…` |
|
||||
| `zipformer-zh-2025` | zh | sherpa-online | Apache-2.0 | 167MB | `5ac51e27981bb4da…` |
|
||||
| `xasr-zh-en-480` | zh, en | sherpa-online | Apache-2.0 | 615MB | `0c3454033d249081…` |
|
||||
| `nemotron35-560ms` | 16 语言(含 ja) | sherpa-online | OpenMDW-1.1 | 682MB | `012e9321373af990…` |
|
||||
|
||||
分发包模型时记得带上许可(尤其 Nemotron 是 OpenMDW-1.1,不是 Apache-2.0)。
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 默认后端:llama.cpp + Qwen3-ASR GGUF
|
||||
./build/live-caption-cli --model M.gguf --mmproj MM.gguf
|
||||
|
||||
# 流式 ONNX 后端:按注册表 id 从模型目录取
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model zipformer-zh-2025
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model nemotron35-560ms --language ja
|
||||
|
||||
# 覆盖模型目录 / 语言提示
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model ... --model-dir /path/to/models
|
||||
```
|
||||
|
||||
## 实测对比(同一批音频,1 线程)
|
||||
|
||||
| 模型 | 中文 | 英文 | 日语 | RTF | 核·秒/秒音频 | 首个字幕 | 体积 | 许可 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| Qwen3-ASR 0.6B(llama) | ✅ | ✅ | ✅ | 0.56 | 4.27 | ~2.5s | 973MB | Apache-2.0 |
|
||||
| zipformer-zh-2025 | ✅ | — | — | 0.098 | **0.10** | **0.48s** | 167MB | Apache-2.0 |
|
||||
| X-ASR-zh-en 480ms | ✅ | ✅ | — | 0.122 | 0.12 | 1.44s | 587MB | Apache-2.0 |
|
||||
| Nemotron 3.5 560ms | ⚠️ 漏字 | ⚠️ 若干错词 | ⚠️ 有错字 | 0.35 | 0.35 | 1.12s | 651MB | OpenMDW-1.1 |
|
||||
|
||||
> 静态模型(zipformer-zh-2025)的多线程是**负优化**:onnxruntime 对小模型开多线程,
|
||||
> 同步/自旋开销会让它更慢(8 线程比 1 线程慢 2.6 倍、CPU 高 28 倍)。所以适配器里固定
|
||||
> `threads = 1`。
|
||||
|
||||
## 设置对话框
|
||||
|
||||
三个页签(模型 / 显示 / 高级),底部三个按钮 **应用 / 取消 / 确定** ——
|
||||
「应用」= 应用但不关闭,方便实时预览(改不透明度、字号时会立刻看到效果)。
|
||||
|
||||
只有**模型 / 识别语言 / 采集设备**变化才会重启识别后端;透明度、字号、行数、位置这类外观改动是即时生效的,不会打断正在进行的转写。
|
||||
|
||||
各设置项的完整说明见 [gui.md](gui.md)。
|
||||
|
||||
## 采集设备选择
|
||||
|
||||
默认跟随系统默认输出;也可以在设置里指定某个输出设备(`--list-devices` 可列出):
|
||||
|
||||
```bash
|
||||
./build/live-caption-cli --list-devices
|
||||
./build/live-caption-cli --cli-live --device alsa_output...HiFi__HDMI1__sink
|
||||
```
|
||||
|
||||
## 完整性校验
|
||||
|
||||
注册表里每个文件都记了 `size` 与 `sha256`:
|
||||
|
||||
- 快速检查(打开/选择模型时):文件存在且**大小**对得上;
|
||||
- 完整校验(设置里「校验完整性」或 `--verify-model <id>`):逐个**重算 sha256**,损坏的文件名会列出来。
|
||||
|
||||
```bash
|
||||
./build/live-caption-cli --verify-model zipformer-zh-2025
|
||||
```
|
||||
|
||||
## 两个坑
|
||||
|
||||
1. **sherpa-onnx 的预编译库是旧 C++ ABI**(`_GLIBCXX_USE_CXX11_ABI=0`),和 Qt 的新 ABI 冲突,
|
||||
C++ API 链接不上。**必须用它的 C API**(`sherpa-onnx/c-api/c-api.h`,`extern "C"`,无名字改写)。
|
||||
2. **末尾要补一小段静音**(`streamFinish()` 里补 0.3s),否则最后一个字会被截掉。
|
||||
但**不需要 `InputFinished`**:实时字幕的音频流永不结束,一句话的边界是「静音」而不是「输入结束」,
|
||||
`InputFinished` 的语义只对文件成立。实测只补静音(不调 `InputFinished`)结果就是完整的。
|
||||
真实场景里那段尾部静音本来就会被喂进去(VAD 判定静音要 0.8s,这 0.8s 已经送给模型了),
|
||||
所以补静音只是个兜底。
|
||||
|
||||
## 自动语言识别
|
||||
|
||||
| 模型 | 自带 LID |
|
||||
|---|---|
|
||||
| Qwen3-ASR | ✅ 输出 `language X`(实测中英都准)|
|
||||
| Nemotron 3.5 | ✅ `language=auto`,但实测会串(日语开头吐韩文)|
|
||||
| X-ASR / zipformer | ❌ 固定语言对,不出语言标签 |
|
||||
|
||||
LID 不必由 ASR 模型提供:Chrome 就带了个独立的 2.5MB `ONDEVICE_langid.tflite`(我们在它的语言包目录里看到了),
|
||||
Windows 同样。sherpa-onnx 也有专门的语种识别模型。所以**「按语言装包 + 用户选语言或小 LID 模型」**是可行路线。
|
||||
|
||||
## 推荐组合(按语言装包)
|
||||
|
||||
| 语言 | 实时预览 | 定稿 |
|
||||
|---|---|---|
|
||||
| 中文 | `zipformer-zh-2025`(最快最准) | Qwen3-ASR |
|
||||
| 英文 | `xasr-zh-en-480` | Qwen3-ASR |
|
||||
| 日语 | `nemotron35-560ms --language ja`(质量一般) | Qwen3-ASR(开源日语第一) |
|
||||
| 其他 | — | Qwen3-ASR(52 语言兜底) |
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# 命令行选项
|
||||
|
||||
两个程序:
|
||||
|
||||
- **`live-caption`** —— 图形界面(悬浮窗 + 托盘 + 设置)。**日常使用不需要任何参数**;
|
||||
下面的参数里,它只关心「后端与模型」「流式参数」「GUI 专用 / 测试专用」几节。
|
||||
- **`live-caption-cli`** —— 命令行版,只链 Qt6::Core,适合无显示环境、脚本、CI。
|
||||
|
||||
两边共用的选项定义在 `apps/common/appcli.h`。
|
||||
`--help` 会用「(默认 X)」把默认值印在说明里。
|
||||
|
||||
## 后端与模型
|
||||
|
||||
| 选项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `--asr-backend <kind>` | `llama` | `llama`(Qwen3-ASR GGUF)或 `sherpa`(流式 ONNX) |
|
||||
| `--asr-model <id>` | — | 模型注册表(`data/models.json`)里的 id;sherpa 后端用它定位文件,llama 后端也可用它走注册表 |
|
||||
| `--model <path>` | — | 主模型 GGUF 路径(架构须为 `qwen3vl`) |
|
||||
| `--mmproj <path>` | — | mmproj GGUF 路径(clip + qwen3a) |
|
||||
| `--model-dir <dir>` | `~/.local/share/live-caption/models` | 覆盖模型存储目录 |
|
||||
| `--language <lang>` | 空 = 自动 | 语言提示(`zh` / `en` / `ja` …),多语言模型需要 |
|
||||
| `--threads <n>` | `8` | 推理线程数(只影响 Qwen3-ASR;流式模型固定单线程) |
|
||||
| `--verbose` | 关 | 输出 llama.cpp / mtmd 的详细日志 |
|
||||
|
||||
> 模型「未安装」时会提示缺失的文件名,并给出 `scripts/fetch-models.sh <id>` 的提示。
|
||||
|
||||
## 流式参数
|
||||
|
||||
参数的选择与实测见 [docs/phase2-streaming.md](phase2-streaming.md)。
|
||||
**这些参数只影响 `llama` 后端**(Qwen3-ASR);`sherpa` 的流式模型只用到「提交粒度」一个参数。
|
||||
同一组参数在 GUI 的「高级 → 流式」里也有(选了流式 ONNX 模型时那一组会置灰)。
|
||||
|
||||
| 选项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `--stream-chunk <sec>` | `2.0` | 累积多少秒音频跑一步(提交粒度) |
|
||||
| `--stream-mode <mode>` | `incremental` | `incremental`(增量 KV 复用)/ `append`(追加式)/ `window`(滑窗) |
|
||||
| `--stream-window <sec>` | `16` | 滑窗上限;仅 `window` 模式,`0` = 不滑窗 |
|
||||
| `--stream-segment <sec>` | `30` | 单段最长时长,超过就提交并重置上下文;`0` = 不限 |
|
||||
| `--unfixed-tokens <n>` | `5` | 前缀回滚:丢掉最后 N 个 token(这些算「不稳定尾部」) |
|
||||
| `--unfixed-chunks <n>` | `2` | 前 N 个 chunk 不带前缀(冷启动) |
|
||||
| `--max-tokens <n>` | `256` | 单段最多生成 token 数 |
|
||||
|
||||
## 运行模式(仅 `live-caption-cli`)
|
||||
|
||||
| 选项 | 说明 |
|
||||
|---|---|
|
||||
| `--file <path>` | 整段转写一个 WAV 后退出(离线精度基线) |
|
||||
| `--stream-file <path>` | 以流式模式转写一个 WAV 后退出(验证流式策略) |
|
||||
| `--cli-live` | 实时转写并只在命令行输出(不开窗口),用于无显示环境 |
|
||||
|
||||
## 采集
|
||||
|
||||
| 选项 | 说明 |
|
||||
|---|---|
|
||||
| `--device <sink>` | 采集源(输出设备的 sink 名);留空 = 跟随系统默认输出 |
|
||||
| `--list-devices` | 列出可选的采集设备后退出(仅 `live-caption-cli`) |
|
||||
|
||||
```bash
|
||||
./build/live-caption-cli --list-devices
|
||||
# alsa_output...HiFi__Speaker__sink ... Speaker [默认]
|
||||
# alsa_output...HiFi__HDMI1__sink ... HDMI / DisplayPort 1 Output
|
||||
./build/live-caption-cli --asr-model zipformer-zh-2025 --cli-live --device alsa_output...HiFi__HDMI1__sink
|
||||
```
|
||||
|
||||
## 辅助
|
||||
|
||||
| 选项 | 说明 |
|
||||
|---|---|
|
||||
| `--verify-model <id>` | 重算 sha256 校验模型完整性后退出(仅 `live-caption-cli`) |
|
||||
|
||||
```bash
|
||||
./build/live-caption-cli --verify-model zipformer-zh-2025
|
||||
# ✅ 中文流式(k2-fsa 官方 2025-06-30) 校验通过
|
||||
```
|
||||
|
||||
## GUI 专用 / 测试专用
|
||||
|
||||
这些只在 `live-caption` 上有效。**除 `--opacity` 外都是给自动化测试用的**,
|
||||
平时不需要:界面本身提供这些功能。
|
||||
|
||||
| 选项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `--opacity <n>` | — | 背景不透明度(20–100),覆盖设置里的值 |
|
||||
| `--no-tray` | — | 不创建托盘图标(测试用;此时 `✕` 会直接退出) |
|
||||
| `--screenshot <path>` | — | 启动后自动截图并退出;同时截折叠态与展开态(`-expanded.png`) |
|
||||
| `--screenshot-delay <sec>` | `6` | 截图前等待秒数 |
|
||||
| `--screenshot-settings <path>` | — | 打开设置对话框、截图后退出 |
|
||||
| `--settings-tab <tab>` | — | 截图设置对话框时先切到某个页签(`0`–`2` 或 `模型`/`显示`/`高级`) |
|
||||
| `--settings-autoclose <how>` | — | 自动操作设置对话框:`reject` / `close` / `accept` / `ok` / `apply`(`ok`/`apply` 是真的去点按钮) |
|
||||
| `--quit-after <sec>` | — | 运行若干秒后优雅退出(测退出路径) |
|
||||
|
||||
`--settings-autoclose` + `--quit-after` 是当初定位「点确定程序就退出」崩溃时留下的复现手段,
|
||||
也可以当作界面交互的冒烟测试:
|
||||
|
||||
```bash
|
||||
for how in reject close accept ok apply; do
|
||||
./build/live-caption --asr-model zipformer-zh-2025 --no-tray \
|
||||
--settings-autoclose $how --quit-after 8
|
||||
echo "$how → 退出码 $?"
|
||||
done
|
||||
```
|
||||
|
||||
## 退出码
|
||||
|
||||
| 码 | 含义 |
|
||||
|---|---|
|
||||
| `0` | 正常结束(含 `--screenshot*`、`--quit-after` 的优雅退出) |
|
||||
| `1` | 启动失败:模型没加载起来(`live-caption-cli` 的 `--verify-model` 校验失败也是 1) |
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# 图形界面(Phase 4)
|
||||
|
||||
`live-caption` 是图形界面程序:悬浮字幕窗 + 系统托盘 + 设置对话框。
|
||||
**不用任何命令行参数就能完整使用**;命令行参数只保留给自动化测试(显式给出时覆盖设置)。
|
||||
|
||||
## 首次运行
|
||||
|
||||
首次启动时如果还没有「已下载且被选中」的模型,程序会先弹出**设置对话框(标题为
|
||||
「实时字幕 — 首次配置」)**,并挡住主流程 —— 下载一个模型、在「当前使用」里选中它,
|
||||
点「确定」之后才会出现字幕窗。
|
||||
|
||||
```
|
||||
第一次启动 → 设置对话框 → 下载模型 → 选择「当前使用」 → 确定 → 悬浮字幕窗
|
||||
```
|
||||
|
||||
## 字幕窗
|
||||
|
||||
| 操作 | 行为 |
|
||||
|---|---|
|
||||
| 拖动 | 移动窗口;位置会被记住 |
|
||||
| 左上角语言标签 | 点击 → 打开设置对话框 |
|
||||
| 底部箭头 `⌄` / `⌃` | 折叠(2 行)/ 展开(8 行) |
|
||||
| 右上角 `✕` | **隐藏到托盘**(不是退出;用托盘菜单可以再显示回来) |
|
||||
|
||||
窗口的文本分两段显示:**已稳定**部分是白色,**尚未稳定**的尾部是灰色。这就是 Chrome
|
||||
实时字幕那种「字一个个长出来、末尾会改」的观感。
|
||||
|
||||
> 没有托盘时(`--no-tray`,或桌面环境不支持托盘)`✕` 会直接退出程序。
|
||||
|
||||
## 托盘
|
||||
|
||||
托盘菜单有三项:
|
||||
|
||||
- **显示/隐藏字幕**
|
||||
- **设置…**
|
||||
- **退出**
|
||||
|
||||
单击托盘图标也会切换字幕窗的显示/隐藏。
|
||||
|
||||
## 设置对话框
|
||||
|
||||
三个页签(模型 / 显示 / 高级),底部三个按钮:
|
||||
|
||||
| 按钮 | 行为 |
|
||||
|---|---|
|
||||
| **应用** | 应用设置但**不关闭**对话框 —— 方便实时预览(改不透明度、字号时立刻能看到效果) |
|
||||
| 取消 | 放弃本次改动(已经用「应用」生效过的改动不会被回滚) |
|
||||
| 确定 | 应用并关闭 |
|
||||
|
||||
**哪些改动要重启识别后端?** 只有**模型 / 识别语言 / 采集设备**,以及高级页里的**流式参数、
|
||||
线程数、模型目录**变化时才会重建后端并重启转写;透明度、字号、行数、灰色尾部这类外观改动是
|
||||
即时生效的,不会打断正在进行的转写。
|
||||
|
||||
### 模型页
|
||||
|
||||
- **模型表格**:列出注册表里的所有模型(名称 / 语言 / 许可 / 状态)。第一列是注册表 id,
|
||||
状态列显示「已安装 / 未安装」,未安装时鼠标悬停会列出缺失的文件名。
|
||||
- **下载**:把选中的模型下到 `~/.local/share/live-caption/models/<id>/`。
|
||||
支持设置下载源(镜像)与代理、断点续传、实时进度。下载完成会自动刷新列表。
|
||||
- **校验完整性**:对选中模型的所有文件**重算 sha256**,与注册表里的期望值比对;
|
||||
失败会列出损坏的文件名(可删除后重新下载)。文件大时需要几秒。
|
||||
- **删除**:删掉该模型已下载的文件。如果删的正是「当前使用」的模型,选择会被清空。
|
||||
- **打开模型目录**:在文件管理器里打开模型存储目录。
|
||||
- **采集设备**:默认「跟随系统默认输出」(即当前默认输出的 monitor)。
|
||||
也可以指定某个具体输出设备(如 HDMI);列不出来或没列全时见
|
||||
[troubleshooting.md](troubleshooting.md)。
|
||||
- **当前使用**:选择实际生效的模型(只列出**已安装**的)。
|
||||
- **识别语言**:语言提示,多语言模型用它(例如 Nemotron 必须指定语言,否则「自动」可能识别成别的语言);
|
||||
「自动检测」= 留空。**候选项按所选模型支持的语言生成** —— 中文模型只给中文,Nemotron 给它的 16 种
|
||||
语言,Qwen3-ASR 给常用语言。改完之后左上角的语言标签会同步更新。
|
||||
- **下载源**:默认 `https://hf-mirror.com`(网络可达性最好的镜像);可改成其它镜像或官方源。
|
||||
- **代理**:不使用 / 跟随系统 / 手动设置(主机、端口、用户名、密码)。
|
||||
|
||||
### 显示页
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 字号 | 字幕文字大小(9–40) |
|
||||
| 用灰色显示尚未稳定的尾部 | 关掉后就只显示已稳定的文本 |
|
||||
| 折叠行数 / 展开行数 | 折叠态与展开态各显示几行 |
|
||||
| 背景不透明度 | 20%–100%,默认 84%(纯黑底,保证任何桌面背景下文字都可读) |
|
||||
|
||||
### 高级页
|
||||
|
||||
**通用**
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 更新粒度(秒) | 累积多少秒音频跑一步;「自动」= 由后端决定(流式模型 0.32s) |
|
||||
|
||||
**流式(只影响 Qwen3-ASR)** —— 这一组对应 llama 后端的流式参数,改动会重启识别后端。
|
||||
选了流式 ONNX 模型(zipformer / X-ASR / Nemotron)时整组会**置灰**,因为那些模型只用「更新粒度」。
|
||||
|
||||
| 项 | 对应命令行 | 说明 |
|
||||
|---|---|---|
|
||||
| 策略 | `--stream-mode` | `incremental`(增量复用,1~2 秒就出字,推荐)/ `append`(追加式,成本平坦但需要大 chunk)/ `window`(早期的对比实现) |
|
||||
| 滑窗上限(秒) | `--stream-window` | 仅 window 模式;「不限」= 不滑窗 |
|
||||
| 单段最长时长(秒) | `--stream-segment` | 超过就提交并重置上下文;「不限」= 不设上限 |
|
||||
| 前缀回滚 token 数 | `--unfixed-tokens` | 回滚丢弃最后 N 个 token —— 它们会显示成灰色的不稳定尾部 |
|
||||
| 冷启动 chunk 数 | `--unfixed-chunks` | 前 N 个 chunk 不带前缀,避免开头重复 |
|
||||
| 单段最多生成 token | `--max-tokens` | 单段生成的 token 上限 |
|
||||
| 线程数 | `--threads` | 只影响 Qwen3-ASR;流式模型固定单线程(多线程反而更慢) |
|
||||
|
||||
**调试**
|
||||
|
||||
| 项 | 对应命令行 | 说明 |
|
||||
|---|---|---|
|
||||
| 输出详细日志 | `--verbose` | 打印 llama.cpp / mtmd 的详细日志(排查加载/推理问题时用) |
|
||||
| 模型目录 | `--model-dir` | 留空 = 默认目录(占位符会显示实际路径);一般不需要改 |
|
||||
|
||||
## 配置文件
|
||||
|
||||
所有设置存在 `QSettings` 里:`~/.config/live-caption/live-caption.conf`,组名 `[app]`。
|
||||
|
||||
```ini
|
||||
[app]
|
||||
modelId=zipformer-zh-2025 ; 当前使用的模型 id
|
||||
language= ; 空 = 自动
|
||||
captureDevice= ; 空 = 跟随系统默认输出
|
||||
opacity=84 fontSize=15 ; 外观
|
||||
showUnstableTail=true
|
||||
collapsedLines=2 expandedLines=8
|
||||
windowX=179 windowY=725 ; 拖动后记录的位置
|
||||
mirrorBase=https://hf-mirror.com
|
||||
proxyMode=0 ; 0=不使用 1=跟随系统 2=手动
|
||||
chunkSec=0 threads=8 ; 高级
|
||||
streamMode=incremental ; 高级:流式参数(只影响 Qwen3-ASR)
|
||||
streamWindowSec=16 streamSegmentSec=30
|
||||
unfixedTokens=5 unfixedChunks=2 maxTokens=256
|
||||
verbose=false modelDir= ; 高级:调试
|
||||
```
|
||||
|
||||
删掉这个文件(或其中某个键)就回到默认值。模型文件在
|
||||
`~/.local/share/live-caption/models/<id>/`,不受这个文件影响。
|
||||
|
||||
## 自动化测试钩子(仅测试用)
|
||||
|
||||
界面本身的行为可以完全用命令行脚本驱动,这些选项平时用不到:
|
||||
|
||||
```bash
|
||||
# 打开设置对话框并截图后退出
|
||||
./build/live-caption --screenshot-settings /tmp/settings.png
|
||||
|
||||
# 自动关掉设置对话框,用来测「关闭/确定/取消/应用」各条路径是否崩溃
|
||||
./build/live-caption --asr-model zipformer-zh-2025 --no-tray \
|
||||
--settings-autoclose {reject|close|accept|ok|apply} --quit-after 8
|
||||
|
||||
# 字幕窗自截图(折叠态 + 展开态)
|
||||
./build/live-caption --asr-model zipformer-zh-2025 --no-tray \
|
||||
--screenshot /tmp/win.png --screenshot-delay 6
|
||||
```
|
||||
|
||||
完整列表见 [cli.md](cli.md)。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,144 @@
|
||||
# 打包(CPack → .deb)
|
||||
|
||||
用 CMake 的 CPack 生成 `.deb`,配置在 [`cmake/Packaging.cmake`](../cmake/Packaging.cmake)。
|
||||
|
||||
## 三条命令
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
(cd build && cpack) # 默认生成器就是 DEB,等价于 cpack -G DEB
|
||||
```
|
||||
|
||||
产物:`build/live-caption_<版本>-<修订>_<架构>.deb`,例如 `live-caption_0.1.0-1_amd64.deb`(约 11MB)。
|
||||
|
||||
```bash
|
||||
dpkg -c build/live-caption_0.1.0-1_amd64.deb # 看文件清单
|
||||
dpkg -I build/live-caption_0.1.0-1_amd64.deb # 看控制信息与依赖
|
||||
sudo apt install ./build/live-caption_0.1.0-1_amd64.deb
|
||||
sudo apt remove live-caption # 卸载(模型文件与用户设置不会被删)
|
||||
```
|
||||
|
||||
> 用 `apt install ./xxx.deb` 而不是 `dpkg -i`:apt 会把上面自动推导出来的依赖一起装好。
|
||||
|
||||
## 包内容
|
||||
|
||||
| 路径 | 说明 |
|
||||
|---|---|
|
||||
| `/usr/bin/live-caption` | 图形界面(悬浮窗 + 托盘 + 设置) |
|
||||
| `/usr/bin/live-caption-cli` | 命令行版(单文件/流式文件/无窗口实时) |
|
||||
| `/usr/bin/live-caption-fetch-models` | 命令行下载模型(`scripts/fetch-models.sh` 装的) |
|
||||
| `/usr/lib/live-caption/` | 包私有共享库:`libsherpa-onnx-c-api.so`、`libonnxruntime.so` |
|
||||
| `/usr/share/applications/live-caption.desktop` | 应用菜单入口 |
|
||||
| `/usr/share/icons/hicolor/scalable/apps/live-caption.svg` | 图标 |
|
||||
| `/usr/share/live-caption/models.json` | 模型注册表(给上面的下载脚本用;程序自己也内嵌了一份) |
|
||||
| `/usr/share/doc/live-caption/` | README 与用户文档 |
|
||||
|
||||
**模型不随包分发**(注册表里有 4 个、合计约 2.4GB)。首次启动时在设置界面里按需下载,
|
||||
也可以装完之后跑:
|
||||
|
||||
```bash
|
||||
live-caption-fetch-models # 列出模型与安装状态
|
||||
live-caption-fetch-models --all # 全部下载
|
||||
```
|
||||
|
||||
## 依赖是怎么确定的
|
||||
|
||||
`CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON` —— 用 `dpkg-shlibdeps` 直接扫二进制,推导出:
|
||||
|
||||
```
|
||||
Depends: libc6 (>= 2.34), libgcc-s1 (>= 4.0), libllama0 (>= 9951+dfsg), libpulse0 (>= 0.99.1),
|
||||
libqt6core6 (>= 6.8.0), libqt6gui6 (>= 6.1.2), libqt6network6 (>= 6.1.2),
|
||||
libqt6widgets6 (>= 6.3.0), libsamplerate0 (>= 0.1.7), libstdc++6 (>= 11)
|
||||
```
|
||||
|
||||
这比手写列表可靠(跟着二进制走,不会漏)。`libllama0` 同时提供 `libllama`、`libmtmd`
|
||||
和 `libllama-common`,所以一个依赖就够。
|
||||
|
||||
包内自带的 sherpa 库是**私有库**:`dpkg-shlibdeps` 通过二进制的 RPATH 找到它们、
|
||||
识别为同包文件,因此不会产生外部依赖。
|
||||
|
||||
需要手动补依赖时:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DLC_DEB_EXTRA_DEPENDS="foo (>= 1.2), bar"
|
||||
```
|
||||
|
||||
## 为什么打包带上 sherpa-onnx
|
||||
|
||||
流式 ONNX 后端(zipformer / X-ASR / Nemotron)依赖 `libsherpa-onnx-c-api.so` 与
|
||||
`libonnxruntime.so`。官方只发预编译 tar 包,**发行版里没有对应包可依赖**,所以默认随包携带
|
||||
(约 32MB 未压缩,deb 里压到约 10MB)。
|
||||
|
||||
关掉它(包变小,但安装后的机器上流式后端起不来):
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DLC_BUNDLE_SHERPA=OFF # 包约 0.5MB,只剩 llama 后端可用
|
||||
```
|
||||
|
||||
许可:sherpa-onnx 是 Apache-2.0,ONNX Runtime 是 MIT,都可以再分发;官方 tar 包里没带
|
||||
LICENSE 文件,自己分发时建议一并附上。
|
||||
|
||||
## RPATH:两个必须写进二进制的路径
|
||||
|
||||
安装后的二进制带这样的 RUNPATH:
|
||||
|
||||
```
|
||||
$ORIGIN/../lib/live-caption:/usr/lib/x86_64-linux-gnu/llama
|
||||
```
|
||||
|
||||
两条都有原因:
|
||||
|
||||
1. `$ORIGIN/../lib/live-caption` —— 找包内自带的 sherpa 库。用 `$ORIGIN` 相对路径,
|
||||
包装到哪个前缀都能用,也不需要 `ldconfig`。
|
||||
2. `/usr/lib/x86_64-linux-gnu/llama` —— `libllama.so.0` / `libmtmd.so.0` 在发行版里放在
|
||||
**子目录** `llama/` 里,而该目录不在 ld 的默认搜索路径(`ldconfig -p` 里看不到它们),
|
||||
也没有 `/etc/ld.so.conf.d` 条目。所以只能靠 RPATH,否则装完直接起不来。
|
||||
|
||||
## 可调选项
|
||||
|
||||
| 选项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `LC_INSTALL` | `ON` | 生成安装与打包规则 |
|
||||
| `LC_BUNDLE_SHERPA` | `ON` | 把 sherpa-onnx 运行时打进包 |
|
||||
| `LC_PACKAGE_STRIP` | `OFF` | 打包时 strip 二进制。发布建议打开;**要用 coredump 调符号就保持关闭** |
|
||||
| `LC_DEB_MAINTAINER` | 占位值 | Debian `Maintainer` 字段,发布前改成真人 |
|
||||
| `LC_DEB_HOMEPAGE` | 空 | Debian `Homepage` 字段;留空则不写这一行 |
|
||||
| `LC_DEB_EXTRA_DEPENDS` | 空 | 覆盖/追加 `Depends` |
|
||||
| `LC_BUILD_TESTS` | `ON` | 打包时用 `-DLC_BUILD_TESTS=OFF` 可以少编测试 |
|
||||
|
||||
例:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
|
||||
-DLC_BUILD_TESTS=OFF -DLC_PACKAGE_STRIP=ON \
|
||||
-DLC_DEB_MAINTAINER="你的名字 <you@example.com>" \
|
||||
-DLC_DEB_HOMEPAGE="https://example.com/live-caption"
|
||||
(cd build && cpack)
|
||||
```
|
||||
|
||||
## 版本号与修订号
|
||||
|
||||
版本来自顶层 `CMakeLists.txt` 的 `project(live-caption VERSION x.y.z)`,
|
||||
Debian 修订号是 `LC_...`/`CPACK_DEBIAN_PACKAGE_RELEASE`(当前 `1`),
|
||||
所以包名形如 `live-caption_0.1.0-1_amd64.deb`。升级时改 `project(... VERSION)`。
|
||||
|
||||
## 排错
|
||||
|
||||
- **`找不到 libmtmd`**:需要 `libllama0`(提供 `libmtmd.so.0`),与开发时同一个包。
|
||||
- **装完之后 `live-caption` 报找不到 `libllama.so.0`**:说明 RPATH 丢了。用
|
||||
`readelf -d /usr/bin/live-caption | grep RUNPATH` 确认里面有
|
||||
`/usr/lib/x86_64-linux-gnu/llama`。
|
||||
- **流式模型报加载失败**:确认 `/usr/lib/live-caption/` 下有那两个 `.so`(即打包时
|
||||
`LC_BUNDLE_SHERPA` 没关掉)。
|
||||
- **菜单里没有图标/条目**:`sudo update-desktop-database /usr/share/applications`、
|
||||
`sudo gtk-update-icon-cache -f /usr/share/icons/hicolor`(`postinst` 里已经会自动做,
|
||||
但某些桌面环境需要重新登录)。
|
||||
|
||||
## 与 Debian 原生打包的关系
|
||||
|
||||
这是 **CPack 生成的二进制包**,不是用 `debian/` + `dh` 源码构建的 Debian 官方包。
|
||||
差异:没有源码包(`.dsc`/`.orig.tar.gz`)、没有 `debian/changelog`、没有 split 调试包
|
||||
(`-dbg`)、也没走 `dh_*` 的一整套规范化。
|
||||
|
||||
要往发行版仓库里送包的话,需要另配 `debian/` 目录;本地分发和内部部署用现在这套就够。
|
||||
@@ -32,6 +32,11 @@
|
||||
|
||||
> 流式含义:模型常驻内存时,处理 2 秒窗口约 0.3 s,滑动窗口 + 提交策略下端到端延迟可做到 **~1 s 级**,与 Chrome 实时字幕同量级。
|
||||
|
||||
> **口径提示**:本页的 RTF ≈ 0.19 是 **`llama-cli` 纯生成**(`-t 8`)的数字。
|
||||
> 程序内走 `libmtmd` 音频编码的实现,实测 RTF ≈ **0.56**(单线程,见
|
||||
> [asr-backends.md](asr-backends.md#实测对比同一批音频1-线程));两个口径都远低于 1.0,
|
||||
> 但引用数字时要注意区分。另外流式 ONNX 后端的 CPU 占用比它低约 35 倍。
|
||||
|
||||
### 2.1 0.6B vs 1.7B 实测对比
|
||||
|
||||
均为 Q8_0 主模型 + Q8_0 mmproj,`-t 8`。
|
||||
|
||||
+148
-32
@@ -1,52 +1,168 @@
|
||||
# Phase 2 计划:原生流式解码
|
||||
# Phase 2:原生流式解码
|
||||
|
||||
目标:把「窗口重转写 + 事后取最长公共前缀」换成模型官方的流式解码 —— **前缀回滚(prefix rollback)**,消除 Phase 1 里「窗口在词中间被切断时模型自己编结尾」的问题。
|
||||
状态:**完成**。准确率与离线转写一致,单步计算稳定在 2s 预算内。
|
||||
|
||||
实现方式:**在 libllama / libmtmd 上自己实现**(只保留一个推理运行时,复用已有的 CMake、模型管理、采集与解析代码)。
|
||||
参考实现:`antirez/qwen-asr`(纯 C,已实现 `--stream` 的前缀回滚与滑窗),其 MODEL.md 逐行记录了官方 Python 实现 `qwen_asr/inference/qwen3_asr.py` 的流式算法,用作对齐参数的对照。
|
||||
> 本文讲的这套「切块 + 前缀回滚 + 增量 KV 复用」是 **llama 后端(Qwen3-ASR)** 的路径
|
||||
> (`IAsr::AsrKind::PrefixRollback`)。Phase 3.5 加的流式 ONNX 后端走的是另一条分支
|
||||
> (`NativeStreaming`:模型自己有状态,上层只喂音频、取当前整句),
|
||||
> 见 [asr-backends.md](asr-backends.md)。GUI 会按所选模型自动选这两条路径,不用手动切。
|
||||
|
||||
## 为什么不需要 vLLM
|
||||
## 两种流式模式(实测对比)
|
||||
|
||||
官方文档写「streaming 只支持 vLLM 后端」,容易误解为依赖 vLLM 特性。实际上流式只是一套**解码策略**:
|
||||
代码里实现了两条流式路径,用 `--stream-mode` 切换。它们对应一个**无法同时满足的三选二**:
|
||||
|
||||
| 目标 | `incremental`(默认) | `append`(追加式) |
|
||||
|---|---|---|
|
||||
| 成本不随说话时长增长 | ❌ | ✅ |
|
||||
| CPU 效率 | RTF 1.06(无段落上限时) | **RTF 0.26** |
|
||||
| 1–2s 就出字 | ✅ | ❌ 需 8s chunk |
|
||||
| 准确率 | ✅(2s 提交 + 8s 编码切片) | ✅(仅 chunk≈8s 时) |
|
||||
|
||||
同一段 62.6s 连续语音:
|
||||
|
||||
| 配置 | 墙钟 | RTF | 平均步 | 最慢步 |
|
||||
|---|---|---|---|---|
|
||||
| `incremental` chunk=2 segment=20 | 35.5s | 0.57 | 1.09s | 1.86s |
|
||||
| `incremental` chunk=2 不限段长 | 67.7s | 1.08 | 2.10s | 4.30s |
|
||||
| `append` chunk=5 | 18.1s | 0.29 | 1.33s | 1.56s |
|
||||
| `append` chunk=8 | **15.2s** | **0.24** | 1.80s | 1.91s |
|
||||
|
||||
`append` 的每步耗时几乎不随总长变化;`incremental` 则线性增长。
|
||||
|
||||
### 为什么 `append` 必须用大 chunk
|
||||
|
||||
准确率对 **chunk 长度**极其敏感,因为编码器(AuT)用的是 **8 秒注意力窗口**(`n_window_infer = 800` 帧 @100Hz)。每块只用自己的长度去编码时:
|
||||
|
||||
| chunk | 中文实测结果 |
|
||||
|---|---|
|
||||
| 2s | ❌ `不排除购房者可以在互。`(每块都被截断,`互联网上下单` 全丢) |
|
||||
| 4s | ⚠️ `不排除购房者可以在互联网上下单,不排除。`(基本对,边界多一个词) |
|
||||
| 8s | ✅ 与离线一致 |
|
||||
|
||||
所以「便宜/平坦」和「1–2s 出字」对 Qwen3-ASR 是互斥的:要准确就得给编码器 8s 上下文,给了就必然 8s 才出一次字。
|
||||
|
||||
### 追加式为什么便宜
|
||||
|
||||
`append` 把音频切成定长段,**每段独立转写后按顺序拼接**(对应 sglang 给 Qwen3-ASR 定的 segment 流式模式):
|
||||
|
||||
- 不做任何前缀重算;
|
||||
- 旧音频不重编码;
|
||||
- KV 每段重置(成本与音频总长无关)。
|
||||
|
||||
而 `incremental` 每步都要把「音频尾部 + 到目前为止的全部文本前缀」按新的音频上下文重算一遍(因果注意力决定了:把新音频插到文本之前,文本之后的 KV 全部作废)。实测拆解显示这一步的代价是 O(N²):
|
||||
|
||||
| 累计音频 | 音频(编码+写KV) | 文本前缀 prefill | 生成 | 合计 |
|
||||
|---|---|---|---|---|
|
||||
| 2.0s | 0.35s | 0.03s | 0.19s | 0.58s |
|
||||
| 46.0s | 1.23s | 1.20s | 0.38s | 2.81s |
|
||||
| 62.6s | 1.46s | **1.53s** | 0.16s | 3.15s |
|
||||
|
||||
「文本前缀 prefill」从 0.03s 涨到 1.53s,占末尾步耗时的一半。
|
||||
|
||||
**踩坑记录**:最初把各段实现成「接在上一轮之后的对话轮」(携带上文),结果模型会**抄上一轮的文本** —— 音频内容明显变了,它还是把上一轮的句子原样再吐一遍(实测:第 1 段是「英文尾 2.4s + 中文 5.6s」,却输出了整句英文)。改成每段独立转写后消失。所以这里的「追加」指的是**结果按顺序拼接**,不是「上下文一直累积」。
|
||||
|
||||
### 追加式的残留问题:段边界重复
|
||||
|
||||
各段互不重叠,所以边界处会把上一段的尾巴再写一遍,例如中文实测:
|
||||
|
||||
```
|
||||
+ 不排除购房者可以在互联网上下单。不排除购房者可以在。
|
||||
+ 在互联网上下单,不排除购房者可以在互联网上下单。 ← "在互联网上下单," 是上一段的尾巴
|
||||
```
|
||||
|
||||
要消除它需要重叠窗口 + 去重,那就是 `incremental` 的做法(也因此贵)。所以:
|
||||
|
||||
- **要字幕质量 → `incremental`(默认)**;
|
||||
- **要省 CPU / 转写长音频 → `append`,chunk 取 5–8s**。
|
||||
|
||||
## 结论
|
||||
|
||||
| 数据 | 结果 |
|
||||
|---|---|
|
||||
| 准确率 | 流式输出与离线转写逐字一致(中/英各自验证) |
|
||||
| 单步计算(incremental,segment≤20s) | 最慢 1.84s(预算 2.0s,提交粒度 2s) |
|
||||
| 整体 RTF | 约 0.59 |
|
||||
| 实现 | 纯 C++,libllama + libmtmd,无 Python |
|
||||
|
||||
## 算法
|
||||
|
||||
官方文档说「streaming 只支持 vLLM 后端」,容易误解为依赖 vLLM 特性。实际上流式只是一套**解码策略**(`qwen_asr/inference/qwen3_asr.py`,`antirez/qwen-asr` 的 MODEL.md 有逐行记录):
|
||||
|
||||
1. 音频按 2s 累积;
|
||||
2. 每次触发时把**已累积的全部音频重新过一遍编码器**(O(n²),被 2s 节奏限制住);
|
||||
3. 解码器 prompt 里带上**上一轮转写文本(去掉最后 5 个 token)**作为 assistant 前缀,从那里继续生成;
|
||||
2. 把音频(连同已有的历史)过编码器;
|
||||
3. 解码器 prompt 里带上**上一轮文本减去最后 `unfixed_token_num` 个 token** 作为 assistant 前缀,从那里继续生成;
|
||||
4. 前 `unfixed_chunk_num` 个 chunk 不带前缀(冷启动);
|
||||
5. 输出 = 前缀 + 新生成部分。
|
||||
|
||||
## 参数(官方代码默认值)
|
||||
参数取代码默认值:`chunk_size_sec=2.0`、`unfixed_token_num=5`、`unfixed_chunk_num=2`。
|
||||
|
||||
| 参数 | 值 | 说明 |
|
||||
|---|---|---|
|
||||
| `chunk_size_sec` | 2.0 s | 音频累积粒度 |
|
||||
| `unfixed_token_num` | 5 | 前缀回滚:丢掉最后 5 个 token 再续写 |
|
||||
| `unfixed_chunk_num` | 2 | 冷启动不开前缀;论文写 4,取保守值 |
|
||||
| 滑窗上限 | ~16 s | 丢弃「文本已提交」对应的音频,把成本从 O(n²) 压到 O(n·窗口) |
|
||||
## 关键发现:编码必须按 8 秒切片对齐
|
||||
|
||||
## 与 Phase 1 原型的差距
|
||||
这是决定准确率的核心。编码器(AuT)按 `n_window_infer = 800` 帧(8s @100Hz)做窗口注意力,并按 100 帧一组做独立卷积。**把音频切得太碎去编码会明显掉准确率**:
|
||||
|
||||
| 已有 | 缺 |
|
||||
| 编码粒度 | 结果 |
|
||||
|---|---|
|
||||
| 2s 节奏的窗口重转写 | 把「上一轮文本 − 最后 5 token」拼进 assistant 前缀 |
|
||||
| mtmd tokenize + eval 的完整路径 | 按 **token** 而非字符回滚(需跟踪生成的 token 序列) |
|
||||
| 语言识别、输出解析、稳定前缀显示 | 滑窗:丢弃已提交文本对应的音频 |
|
||||
| monitor 采集 + 重采样 | 用「已提交 token 数」定义稳定边界,替换事后取交集 |
|
||||
| 2s | ❌ `dinner, or dinner,` / `boiled bruised potatoes` / `thick, thick` |
|
||||
| 4s | ⚠️ 一处错(`browned bruised`、`thick, black`) |
|
||||
| **8s** | ✅ 与离线逐字一致 |
|
||||
|
||||
> 注意:Phase 1 的「字符最长公共前缀」是错的替代品,官方的定义是「丢最后 5 个 token」。
|
||||
所以实现上**按 8s 对齐切片**:排满 8s 的切片固化进 KV 永久复用;尾部不满 8s 的部分每步重编码(临时的,下一步丢弃)。
|
||||
|
||||
## 顺带简化:去掉 VAD
|
||||
## 实现:增量 KV 复用
|
||||
|
||||
官方明确不使用 VAD(模型自己处理静音;只有非流式长音频才用「在切点 ±5s 内找 100ms 最低能量点」切段)。流式模式下可以整个删掉能量 VAD,少一个需要调参的组件。
|
||||
与「每步重编码整个窗口」(早期做法)不同:
|
||||
|
||||
## Spike(先验证,再改产品代码)
|
||||
- 新音频只编码一次;
|
||||
- 已解码的音频留在 KV cache 里,不再重编码、也不再重新 prefill;
|
||||
- 每步只做:`llama_memory_seq_rm` 回退到音频末尾 → 追加新音频(`mtmd_helper_eval_chunk_single`,它内部处理 M-RoPE 与分批)→ 解码音频之后的 prompt 文本与前缀 → 贪心生成。
|
||||
|
||||
1. **效果**:同一段音频,对比「离线转写」与「带前缀回喂的流式」输出,确认流式结果连贯、不再编结尾。
|
||||
2. **延迟**:实测 2s 节奏下的单步耗时,重点看窗口涨到 16s 时是否仍跟得上(每步预算 < 2s)。
|
||||
3. 以上两条通过后,才把它落进 `Qwen3Asr`,并补一个流式模式的实机测试脚本。
|
||||
因此单步成本与音频总长无关,只与**当前段的长度**有关。
|
||||
|
||||
## 风险
|
||||
对比(62.6s 英文音频,chunk=2s):
|
||||
|
||||
- **成本**:每步重编码累积音频,窗口越大越慢;若 16s 窗口跟不上,需改为「复用 KV cache + 只编码新 chunk」,并用 `llama_memory_seq_rm` 做回滚。
|
||||
- **前缀注入方式**:需要确认把文本前缀拼在 chat template 的 assistant 头之后,mtmd 能否正确切分(预期:`[text]<media>[text]` 三段,前缀属于第三段)。
|
||||
- **吞吐**:前缀越长,每步 prefill 越贵;滑窗是必须的,不是优化项。
|
||||
| 做法 | 墙钟 | RTF | 最慢单步 |
|
||||
|---|---|---|---|
|
||||
| 每步重编码整个窗口,window=4s | 32.9s | 0.53 | 1.39s(但准确率在窗口滑动时抖动) |
|
||||
| 每步重编码整个窗口,window=16s | 89.0s | 1.42 | 3.93s ❌ |
|
||||
| **增量 KV 复用 + 8s 切片** | 41.2s | 0.66 | **1.89s ✅** |
|
||||
|
||||
## 单段时长上限
|
||||
|
||||
解码器对 KV 的注意力随总长增长,所以**段不能无限长**:
|
||||
|
||||
| 单段上限 | RTF | 最慢单步 | 超预算步数 |
|
||||
|---|---|---|---|
|
||||
| 20s | 0.66 | 1.89s | 0/32 ✅ |
|
||||
| 30s | 0.63 | 2.23s | 1/32 ⚠️ |
|
||||
| 不限 | 1.04 | 3.62s | 15/32 ❌ |
|
||||
|
||||
真实字幕场景里句子之间本来就有静音,应该由**静音检测**分段(Phase 3 接入实时链路时做)。当前用 `--stream-segment`(默认 30s)作为兜底上界,超过即提交并重置上下文,历史正文会保留并继续拼接。
|
||||
|
||||
## 过程中修掉的问题
|
||||
|
||||
1. **拼接错**:`Result::text` 只是新生成的部分,忘了接回前缀 —— 看起来像"算法不工作",其实只是显示拼接错。
|
||||
2. **缝隙缺空格**:`parseAsrOutput` 的 `trim()` 吃掉了续写开头那个空格(`potatoesand`)。改用未 trim 的 `raw` 拼接。
|
||||
3. **分段后重复**:多段拼接时 `parseAsrOutput` 用 `rfind` 定位,只保留最后一个语言头之后的内容,导致前面的正文被丢掉。改为逐段剥离头部再拼接正文。
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 流式转写(默认 incremental:8s 切片 + 前缀回滚 + 2s 提交)
|
||||
./build/live-caption-cli --model MODEL --mmproj MMPROJ \
|
||||
--stream-file audio_16k_mono.wav [--stream-chunk 2] [--stream-segment 30]
|
||||
|
||||
# 追加式:成本平坦、省 CPU,但需要大 chunk 才准确
|
||||
./build/live-caption-cli --model MODEL --mmproj MMPROJ \
|
||||
--stream-file audio_16k_mono.wav --stream-mode append --stream-chunk 8
|
||||
|
||||
# 对比用:最早的"重编码整个窗口"实现
|
||||
./build/live-caption-cli ... --stream-mode window --stream-window 4
|
||||
```
|
||||
|
||||
相关参数:`--stream-mode`(incremental / append / window)、`--stream-chunk`(提交粒度)、`--stream-segment`(单段上限)、`--stream-window`(仅 window 模式)、`--unfixed-tokens`、`--unfixed-chunks`。
|
||||
|
||||
## 遗留
|
||||
|
||||
- 实时链路接入时用**静音检测**代替固定 `--stream-segment` 分段。
|
||||
- 目前每段结束都会重置语言检测;跨段语言切换的表现待观察。
|
||||
- 边界标点偶有差异(分段处 `—`/`,` 之类),不影响内容。
|
||||
@@ -0,0 +1,94 @@
|
||||
# Phase 3:Qt 悬浮字幕窗
|
||||
|
||||
状态:**完成**。悬浮窗可用,已接入实时采集 + 流式转写。
|
||||
(窗口之外的交互 —— 托盘、设置对话框、应用内下载 —— 属于 Phase 4,见
|
||||
[docs/gui.md](gui.md)。本文记录 Phase 3 当时的形态,并在末尾列出后续变化。)
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 已实现
|
||||
|
||||
- **悬浮窗**:无边框、半透明深色圆角、始终置顶、不接受焦点(`Qt::FramelessWindowHint | WindowStaysOnTopHint | Tool | WindowDoesNotAcceptFocus`),可拖动。
|
||||
- **折叠 / 展开**:折叠两行、展开八行,底部箭头切换(折叠态 `⌄`、展开态 `⌃`)。
|
||||
行数可在设置里改(Phase 4)。
|
||||
- **语言标签**:左上角圆角 pill,显示识别到的语言(英语 / 中文 …);点击发 `languageClicked`
|
||||
—— Phase 4 起就是用它打开设置对话框。
|
||||
- **稳定/不稳定区分**:已稳定文本白色,不稳定尾部灰色 —— 与 CLI 版一致,也是 Chrome 那种"字长出来"的观感。
|
||||
灰色尾部可以用设置里的「用灰色显示尚未稳定的尾部」关掉(Phase 4)。
|
||||
- **背景**:**黑色 + 可调不透明度**(不是全透明;纯黑底才能保证任何桌面背景下文字都可读)。
|
||||
默认 84%,范围限制 20~100,设置界面里是可拖的滑块(Phase 4),`--opacity` / `setPanelOpacity()` 也可调。
|
||||
- **关闭**:右上角 `✕`。Phase 4 起它的行为是**隐藏到托盘**(否则关掉就没法再打开了);
|
||||
只有在 `--no-tray` 或托盘不可用时才真正退出。
|
||||
- **实时链路**:采集默认输出的 monitor → 流式转写 → 信号推给窗口,全部在主线程外的工作线程里跑。
|
||||
|
||||
## 实时分段
|
||||
|
||||
Phase 2 的结论是段不能无限长(解码器对 KV 的注意力随总长增长)。Phase 3 用**静音检测**决定段边界:
|
||||
|
||||
- 能量 VAD(噪声底用"快降慢升"的最小值跟踪,见 Phase 1 的教训);
|
||||
- 检测到语音才开始把音频送进引擎,并保留 250ms 前导避免吃掉词头;
|
||||
- **静音期间完全不送音频**:早期版本会把静音也喂进模型,模型对静音产生了幻觉(英文语音前冒出一个 `嗯。`);
|
||||
- 静音超过 0.8s 就收束这一段(提交文本、清空 KV),下一段重新开始。
|
||||
|
||||
`--stream-segment`(默认 30s)仍作为兜底上界,设置界面对应「高级 → 单段最长时长」。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```
|
||||
src/
|
||||
├─ captionwindow.{h,cpp} # 悬浮窗
|
||||
├─ livetranscriber.{h,cpp} # 采集 + VAD + 分段 + 流式引擎(QObject)
|
||||
├─ streamingasr.{h,cpp} # 流式策略(前缀回滚、切片、分段)
|
||||
├─ qwen3asr.{h,cpp} # 进程内推理(libllama + libmtmd)
|
||||
├─ audio.{h,cpp} # WAV 读取 + monitor 采集 + 重采样
|
||||
└─ transcript.{h,cpp} # 输出解析与语言名映射
|
||||
```
|
||||
|
||||
> 目录后来重排过:`captionwindow` / `livetranscriber` 现在在 `src/ui/`,
|
||||
> 其余在 `src/core/`,模型管理独立成 `src/models/`。见 [README 的代码结构](../README.md#代码结构)。
|
||||
|
||||
## 过程中踩的坑
|
||||
|
||||
1. **静音幻觉**:第一版把采集到的静音也喂给了模型,模型对静音产生幻觉,英文语音前面冒出一个 `嗯。`。改为静音期间完全不送音频。
|
||||
2. **自定义 QWidget 子类的样式表背景不生效**:`CaptionWindow { background-color: rgba(0,0,0,215) }` 这条规则在真实渲染时**根本没画**,面板全透明,只有文字和按钮浮在桌面上。原因是 Qt 不会为自定义 `QWidget` 子类绘制样式表背景(需要 `WA_StyledBackground`,或自己画)。改成在 `paintEvent()` 里用 `QPainter::drawRoundedRect` 画底板 —— 这也是 `WA_TranslucentBackground` 顶层窗口的推荐做法。
|
||||
3. **验证方法骗了自己**:`QWidget::grab()` 的产物当时是合成到**深灰底色**上看的,「黑色 + 84%」和「全透明」在深色背景上几乎看不出区别,于是把第 2 条盖住了。改成**直接检查像素 alpha**(面板中央应为 `(0,0,0,≈214)`、圆角外应为 `(0,0,0,0)`),并合成到亮色背景上复核。
|
||||
4. **DPI 警告不关本程序的事**:`setHighDpiScaleFactorRoundingPolicy must be called before creating the QGuiApplication instance` 连 5 行的空白 Qt 程序也会打印 —— 是 Deepin 会话环境设了 `QT_SCALE_FACTOR_ROUNDING_POLICY` 导致的。
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 悬浮窗程序(图形界面,Phase 4 起带托盘与设置)
|
||||
./build/live-caption
|
||||
|
||||
# 调整背景不透明度(20-100)—— 这是 GUI 程序的选项
|
||||
./build/live-caption --opacity 60
|
||||
|
||||
# 无窗口、纯命令行实时(便于在无显示环境调试)
|
||||
./build/live-caption-cli --asr-backend sherpa --asr-model zipformer-zh-2025 --cli-live
|
||||
|
||||
# 自截图(验证渲染,不依赖外部截图工具);会依次截折叠态与展开态
|
||||
./build/live-caption --asr-backend sherpa --asr-model zipformer-zh-2025 \
|
||||
--no-tray --screenshot out.png --screenshot-delay 12
|
||||
```
|
||||
|
||||
> 自截图产物带 alpha 通道;要判断不透明度是否正确,**直接看像素 alpha**,不要靠肉眼看合成效果。
|
||||
> 所有选项见 [docs/cli.md](cli.md)。
|
||||
|
||||
## Phase 3 之后的变化(Phase 4)
|
||||
|
||||
- ✕ 从「退出」改成「隐藏到托盘」,并加了托盘图标与菜单;
|
||||
- 语言标签点击 → 打开设置对话框(模型下载/选择、语言、显示、采集设备、下载源与代理、校验);
|
||||
- 背景不透明度、字号、行数、灰色尾部、窗口位置全部进了设置界面并持久化(`QSettings`);
|
||||
- **采集设备可选**(原来固定跟随启动时的默认输出,切到 HDMI 不会跟着变);
|
||||
- 细节见 [docs/gui.md](gui.md)。
|
||||
|
||||
## 已知限制 / 后续
|
||||
|
||||
- X11 下置顶与定位都正常;Wayland 下需要 layer-shell,属于 Phase 5(见 [docs/troubleshooting.md](troubleshooting.md))。
|
||||
- 界面尚未做 HiDPI 之外的适配(当前主屏宽度 72%、最大 900 逻辑像素)。
|
||||
@@ -0,0 +1,99 @@
|
||||
# 测试
|
||||
|
||||
## 分层
|
||||
|
||||
| 目标 | 依赖 | 说明 |
|
||||
|---|---|---|
|
||||
| `livecaption_core` | 无 Qt | 全部业务逻辑;单元测试只依赖它 |
|
||||
| `livecaption_models` | Qt6::Core / Network | 注册表、安装检查、sha256 校验、应用内下载 |
|
||||
| `livecaption_ui` | Qt6::Widgets | 悬浮窗、设置对话框、Qt 适配层 |
|
||||
| `live-caption` | ui + models | 悬浮窗程序 |
|
||||
| `live-caption-cli` | core + models + Qt6::Core | 命令行程序(**不链接 Qt Widgets**) |
|
||||
| `tst_*` | core + Qt6::Test | 单元测试 |
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
cmake -S . -B build && cmake --build build -j
|
||||
ctest --test-dir build --output-on-failure # 也可以单独跑 build/tests/tst_xxx
|
||||
```
|
||||
|
||||
单元测试**不需要模型文件,也不需要显示环境**,秒级完成。目前 4 套:
|
||||
|
||||
| 测试 | 覆盖 |
|
||||
|---|---|
|
||||
| `tst_streamingasr` | 流式策略:拼接、分段、已稳定/不稳定尾部、冷启动前缀 |
|
||||
| `tst_livepipeline` | 实时管线:静音过滤、不规则 chunk 不丢样本、静音分段 |
|
||||
| `tst_vad` | 能量 VAD(轻话音的检测) |
|
||||
| `tst_transcript` | 输出解析与语言名映射 |
|
||||
|
||||
## 为什么能这样测
|
||||
|
||||
关键是把推理后端抽象成 `IAsr`(`src/core/iasr.h`),测试里换成 `tests/fakeasr.h` 的 `FakeAsr`:
|
||||
|
||||
- 可以**脚本化**每一次 `streamAppend` 返回什么文本;
|
||||
- 记录每次拿到的前缀、音频样本数、以及 `streamReset` 的调用次数;
|
||||
- `dropLastTokens` 用"空格分词"模拟词表,并保留原有格式。
|
||||
|
||||
另外 `LivePipeline` 刻意不带 Qt 依赖、并且把「送音频」拆成同步的 `process()`,所以测试可以直接喂音频,不必碰 PulseAudio。
|
||||
|
||||
## 覆盖的回归用例
|
||||
|
||||
这些用例对应的都是开发过程中**实际踩到**的坑:
|
||||
|
||||
| 测试 | 对应的坑 |
|
||||
|---|---|
|
||||
| `tst_streamingasr.keepsJoiningSpace` | 用 `trim()` 过的文本拼接,导致续写缺空格(`potatoesand`) |
|
||||
| `tst_streamingasr.segmentsAccumulateWithoutLosingEarlierText` | 多段拼接时只保留最后一个语言头之后的内容,前面正文丢失 |
|
||||
| `tst_streamingasr.committedDropsUnstableTail` | 已提交 / 不稳定尾部的划分 |
|
||||
| `tst_streamingasr.flushCommitsEverything` | 流结束时尾部被丢掉 |
|
||||
| `tst_streamingasr.coldStartHasNoPrefix` | 冷启动阶段不应回喂前缀 |
|
||||
| `tst_livepipeline.silenceIsNotForwarded` | 静音被送进模型导致幻觉(英文语音前冒出 `嗯。`) |
|
||||
| `tst_livepipeline.noSamplesDroppedAcrossIrregularChunks` | 工作线程丢样本(余数没接上),造成假静音与截断 |
|
||||
| `tst_livepipeline.silenceEndsSegment` | 静音收束分段 |
|
||||
| `tst_vad.quietSpeechIsDetected` | 噪声底用均值跟踪,把很轻的话音全判成静音 |
|
||||
| `tst_transcript.*` | 输出解析与语言名映射 |
|
||||
| `tst_transcript.isoCodeDisplayName` / `registryLanguagesAllHaveDisplayNames` | 设置里的语言提示用的是 ISO 码(`zh`/`uk`…),漏了显示名的话「识别语言」下拉会直接露出 `uk` 这种码 |
|
||||
|
||||
写测试的过程中还**抓到一个真 bug**:段恰好结束在 chunk 边界(没有待处理音频)时,`flush()` 只提交"已稳定"部分,最后几个词会被丢掉。已修(用完整文本 `lastRawFull_` 提交)。
|
||||
|
||||
## 界面 / 集成测试钩子
|
||||
|
||||
界面与真实音频链路不做单元测试,但留有可脚本化的入口(全部选项见 [cli.md](cli.md)):
|
||||
|
||||
```bash
|
||||
# 设置对话框各条退出路径的冒烟测试(当初定位「点确定就退出」的崩溃就是靠它)
|
||||
for how in reject close accept ok apply; do
|
||||
./build/live-caption --asr-model zipformer-zh-2025 --no-tray \
|
||||
--settings-autoclose $how --quit-after 8
|
||||
echo "$how → 退出码 $?"
|
||||
done
|
||||
|
||||
# 界面渲染自截图(折叠态 + 展开态),不依赖外部截图工具
|
||||
./build/live-caption --asr-model zipformer-zh-2025 --no-tray \
|
||||
--screenshot /tmp/win.png --screenshot-delay 6
|
||||
./build/live-caption --screenshot-settings /tmp/settings.png
|
||||
|
||||
# 模型完整性与采集设备(不需要显示环境)
|
||||
./build/live-caption-cli --verify-model zipformer-zh-2025
|
||||
./build/live-caption-cli --list-devices
|
||||
```
|
||||
|
||||
崩溃时用 `coredumpctl list` / `coredumpctl info <PID>` 看调用栈。
|
||||
|
||||
## 尚未覆盖
|
||||
|
||||
以下几类需要真模型或真实音频设备,属于集成测试,没放进单元测试:
|
||||
|
||||
- **8s 编码切片对齐**:这是准确率的决定性因素(切 2s 会明显掉准确率),但必须用真模型跑才能验证。
|
||||
- **增量 KV 复用的单步延迟**:需要真模型才能测。
|
||||
- 采集链路(PulseAudio/PipeWire 的 monitor 源、设备枚举)。
|
||||
- GUI 渲染的**像素级断言**(目前只有人工看截图)。
|
||||
|
||||
这些目前靠 `experiments/` 下的脚本与实机验证(见 `docs/phase0..3`)。
|
||||
|
||||
## 后续可加
|
||||
|
||||
- 给需要模型的集成测试打 CTest label(如 `model`),默认跳过,用环境变量指模型路径时才跑。
|
||||
- GUI 的渲染回归:已有的 `--screenshot` 自截图,可以断言面板像素 alpha(`(0,0,0,214)`),避免再次出现"样式表背景对自定义 QWidget 不生效 → 明明想半透明结果全透明"这类问题。
|
||||
- 给 `ModelStore::verify` 加一个用临时文件构造损坏模型的单元测试(现在只在集成层面手工验证过)。
|
||||
@@ -0,0 +1,94 @@
|
||||
# 常见问题
|
||||
|
||||
## 点 `✕` 之后窗口不见了
|
||||
|
||||
这是设计如此:**`✕` 是隐藏到托盘**,不是退出(否则关掉就再也没法打开了)。
|
||||
用托盘菜单的「显示/隐藏字幕」或单击托盘图标可以再显示回来;要退出用托盘菜单的「退出」。
|
||||
|
||||
如果连托盘图标也没有(桌面环境不支持托盘,或用 `--no-tray` 启动),`✕` 会直接退出程序。
|
||||
|
||||
## 首次启动弹出设置对话框
|
||||
|
||||
没有「已下载且被选中」的模型时,程序必须先让你准备一个模型才能工作,所以会先弹设置。
|
||||
在「模型」页选一个模型点「下载」,然后在「当前使用」里选中它,点「确定」即可。
|
||||
直接点「取消」= 放弃启动(程序退出)。
|
||||
|
||||
## 没有字幕 / 转写全是空白
|
||||
|
||||
按顺序排查:
|
||||
|
||||
1. **系统真的在播放声音吗?** 采集的是「正在播放的音频」,没有播放就没有字幕。
|
||||
2. **采集设备是否选错?** 默认跟随**系统默认输出**。如果声音是从 HDMI 出去的、而默认输出是
|
||||
Speaker(或反过来),就会采到静音。用 `--list-devices` 看有哪些设备,在设置里显式指定一个。
|
||||
```bash
|
||||
./build/live-caption-cli --list-devices
|
||||
```
|
||||
3. **音量和静音状态**:确认系统和该应用的音量不为 0、没有静音。
|
||||
4. 从终端启动看输出,采集/加载失败会打印原因:
|
||||
```bash
|
||||
./build/live-caption # 或 ./build/live-caption-cli --cli-live ...
|
||||
```
|
||||
|
||||
## 提示「模型未安装」/ 缺失某些文件
|
||||
|
||||
模型文件不完整。两种办法:
|
||||
|
||||
- 在设置对话框里选中该模型 → 「校验完整性」看哪些文件坏了 → 「删除」后重新「下载」;
|
||||
- 命令行:`./build/live-caption-cli --verify-model <id>` 查看,`./scripts/fetch-models.sh <id>` 重新下。
|
||||
|
||||
## 「校验失败,损坏的文件: …」
|
||||
|
||||
说明文件内容与注册表里的 sha256 对不上(下载被截断、磁盘问题等)。在设置里**删除该模型再重新下载**
|
||||
即可。下载支持断点续传,网络抖动不会前功尽弃。
|
||||
|
||||
## 下载很慢 / 下载失败
|
||||
|
||||
- 默认下载源是 `https://hf-mirror.com`(实测可达性最好)。可在设置里换成别的镜像或官方源。
|
||||
- 需要走代理时,在设置里把「代理」设为「跟随系统」或「手动设置」并填主机/端口/账号。
|
||||
- 大模型有几百 MB~1GB,首次下载慢是正常的;同一个文件不会重复下载。
|
||||
|
||||
## 日语 / 其它语言效果不好
|
||||
|
||||
这是模型能力问题,不是 bug。结论见 [asr-backends.md](asr-backends.md#推荐组合按语言装包) 的推荐组合:
|
||||
|
||||
| 语言 | 建议 |
|
||||
|---|---|
|
||||
| 中文 | `zipformer-zh-2025`(最快最准)或 X-ASR |
|
||||
| 英文 | `xasr-zh-en-480` |
|
||||
| 日语 | `nemotron35-560ms` + 设置里把「识别语言」改成**日语**(不指定语言会串) |
|
||||
| 其它 | `qwen3-asr-0.6b-q8`(52 语言兜底,CPU 占用高但最准) |
|
||||
|
||||
注意:多语言模型(Nemotron / Qwen3-ASR)**要在设置里选对语言**,否则「自动」可能识别成别的语言。
|
||||
|
||||
## Wayland 下窗口不置顶 / 位置不对
|
||||
|
||||
X11 下正常。Wayland 没有通用的「置顶悬浮层」协议,需要 `wlr-layer-shell`,属于 Phase 5。
|
||||
当前建议在 X11 会话下使用。
|
||||
|
||||
## 构建时警告「未找到 sherpa-onnx,流式 ONNX 后端将不可用」
|
||||
|
||||
正常,说明流式后端被跳过了。要启用:
|
||||
|
||||
```bash
|
||||
ls ~/.local/opt/sherpa-onnx/include/sherpa-onnx/c-api/c-api.h
|
||||
cmake -S . -B build -DSHERPA_ONNX_ROOT=$HOME/.local/opt/sherpa-onnx
|
||||
```
|
||||
|
||||
它需要自带的 `libonnxruntime.so`(`ldd build/live-caption` 可以确认解析到了)。
|
||||
|
||||
## 启动时打印 `setHighDpiScaleFactorRoundingPolicy must be called…`
|
||||
|
||||
与本事无关:一个 5 行的空白 Qt 程序在同样的会话里也会打印。是桌面会话设了
|
||||
`QT_SCALE_FACTOR_ROUNDING_POLICY` 导致的,可以忽略。
|
||||
|
||||
## Qwen3-ASR 的 GGUF 装不进去(加载失败)
|
||||
|
||||
模型与运行时**必须锁版本**:只有 ggml-org 官方 GGUF(`general.architecture = qwen3vl`)能用;
|
||||
社区量化常见的是 `qwen3asr` / `qwen3_asr`,不兼容。细节见
|
||||
[phase0-verification.md](phase0-verification.md)。
|
||||
|
||||
## 点了「确定」程序就退出了
|
||||
|
||||
这是早期版本的一个 bug(`QApplication` 默认「最后一个窗口关闭 = 退出」,而首次启动时设置对话框
|
||||
正是唯一窗口),**已经修好**。如果还在复现,请重新构建后再试;仍复现请附上
|
||||
`coredumpctl info <PID>` 的调用栈。
|
||||
@@ -1,5 +1,9 @@
|
||||
# Phase 0 验证实验
|
||||
|
||||
> **历史文档**:Phase 0 的结论仍然有效(本页的数字与 [docs/phase0-verification.md](../../docs/phase0-verification.md) 一致),
|
||||
> 但当时的脚本是临时实验脚本,现行入口是 GUI(`./build/live-caption`)与
|
||||
> `./build/live-caption-cli`;模型由注册表 `data/models.json` 管理,见 [docs/cli.md](../../docs/cli.md)。
|
||||
|
||||
目标:在动手写 C++/Qt 之前,先证实三个关键假设。
|
||||
|
||||
1. **系统播放音频可采集**:默认 sink 的 `monitor` 源能被读到。
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
目标:把 `docs/phase0-verification.md` 验证过的链路写成一个真正的 C++/Qt/CMake 项目骨架,并在命令行跑通「采集系统输出 → 实时转写 → 打印」。
|
||||
UI 悬浮窗留到 Phase 2。
|
||||
|
||||
> **历史文档**:这里记的是 Phase 1 当时的样子。代码后来重排成了 `src/core` + `src/ui` +
|
||||
> `src/models` + `apps/{gui,cli}`,入口是 `./build/live-caption`(图形界面)和
|
||||
> `./build/live-caption-cli`(命令行);模型改成按注册表 `data/models.json` 取,不再是手工
|
||||
> 传 `--model`/`--mmproj`。现行用法见 [README](../../README.md) 与
|
||||
> [docs/cli.md](../../docs/cli.md)。
|
||||
|
||||
## 目录
|
||||
|
||||
```
|
||||
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把模型注册表里的模型下载到应用数据目录(QStandardPaths::AppDataLocation)。
|
||||
#
|
||||
# 用法:
|
||||
# ./fetch-models.sh # 列出所有模型和安装状态
|
||||
# ./fetch-models.sh <id> [...] # 下载指定模型
|
||||
# ./fetch-models.sh --all # 下载全部
|
||||
#
|
||||
# 目录规则(与程序里 ModelStore 保持一致):
|
||||
# ${XDG_DATA_HOME:-~/.local/share}/live-caption/models/<id>/
|
||||
set -euo pipefail
|
||||
|
||||
SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# 注册表位置:既支持在源码树里跑(<repo>/scripts/ 与 <repo>/data/),
|
||||
# 也支持装到系统之后跑(/usr/bin/ 与 /usr/share/live-caption/)。
|
||||
REG="${LIVE_CAPTION_REGISTRY:-}"
|
||||
if [ -z "$REG" ]; then
|
||||
for cand in "$SELF/../data/models.json" \
|
||||
"$SELF/../share/live-caption/models.json" \
|
||||
"/usr/share/live-caption/models.json" \
|
||||
"/usr/local/share/live-caption/models.json"; do
|
||||
if [ -f "$cand" ]; then REG="$(cd "$(dirname "$cand")" && pwd)/$(basename "$cand")"; break; fi
|
||||
done
|
||||
fi
|
||||
DEST="${XDG_DATA_HOME:-$HOME/.local/share}/live-caption/models"
|
||||
|
||||
[ -n "$REG" ] && [ -f "$REG" ] || {
|
||||
echo "找不到模型注册表(models.json)。" >&2
|
||||
echo "可用 LIVE_CAPTION_REGISTRY=<path> 指定。" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
ids=$(python3 -c "
|
||||
import json,sys
|
||||
d=json.load(open('$REG'))
|
||||
print(' '.join(m['id'] for m in d['models']))")
|
||||
|
||||
show_status() {
|
||||
python3 - "$REG" "$DEST" <<'PY'
|
||||
import json, os, sys
|
||||
reg, dest = sys.argv[1], sys.argv[2]
|
||||
d = json.load(open(reg))
|
||||
for m in d['models']:
|
||||
mid = m['id']; mdir = os.path.join(dest, mid)
|
||||
files = m['files']
|
||||
have = sum(1 for f in files.values() if os.path.exists(os.path.join(mdir, f['name'])))
|
||||
total = len(files)
|
||||
mark = "已安装" if have == total else ("部分" if have else "未安装")
|
||||
langs = ",".join(m['languages'][:4]) + ("…" if len(m['languages']) > 4 else "")
|
||||
print(f" [{have}/{total} {mark}] {mid:22s} {langs:18s} {m.get('license','')}")
|
||||
print(f" {m['name']}")
|
||||
PY
|
||||
}
|
||||
|
||||
download_one() {
|
||||
local id="$1"
|
||||
local dir="$DEST/$id"
|
||||
mkdir -p "$dir"
|
||||
echo "==> $id → $dir"
|
||||
python3 - "$REG" "$id" <<'PY' | while IFS=$'\t' read -r name url; do
|
||||
import json, sys
|
||||
d = json.load(open(sys.argv[1])); mid = sys.argv[2]
|
||||
m = next(x for x in d['models'] if x['id'] == mid)
|
||||
for f in m['files'].values():
|
||||
print(f"{f['name']}\t{f['url']}")
|
||||
PY
|
||||
if [ -f "$dir/$name" ]; then
|
||||
echo " 已存在,跳过: $name"
|
||||
continue
|
||||
fi
|
||||
echo " 下载 $name"
|
||||
if command -v aria2c >/dev/null 2>&1; then
|
||||
aria2c -x16 -s16 -k4M --summary-interval=0 -d "$dir" -o "$name" "$url" >/dev/null
|
||||
else
|
||||
curl -fL --progress-bar -o "$dir/$name" "$url"
|
||||
fi
|
||||
done
|
||||
echo " 完成"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
"" ) echo "模型存储目录: $DEST"; echo; show_status ;;
|
||||
--all) shift; for id in $ids; do download_one "$id"; done ;;
|
||||
*) for id in "$@"; do
|
||||
echo "$ids" | tr ' ' '\n' | grep -qx "$id" || { echo "未知模型: $id" >&2; exit 1; }
|
||||
download_one "$id"
|
||||
done ;;
|
||||
esac
|
||||
@@ -149,7 +149,106 @@ bool readWavMono(const std::string & path, int targetRate,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 实时采集:默认 sink 的 monitor
|
||||
// 枚举输出设备
|
||||
// ---------------------------------------------------------------------------
|
||||
namespace {
|
||||
|
||||
// 枚举时用的上下文。注意:回调里**必须** signal 主循环,
|
||||
// 否则 pa_threaded_mainloop_wait 会一直等下去(这里踩过一次坑)。
|
||||
struct SinkListCtx {
|
||||
std::vector<AudioOutputDevice> * out = nullptr;
|
||||
std::string * defaultSink = nullptr;
|
||||
pa_threaded_mainloop * ml = nullptr;
|
||||
};
|
||||
|
||||
void sinkInfoCb(pa_context * /*c*/, const pa_sink_info * info, int /*eol*/, void * userdata)
|
||||
{
|
||||
auto * ctx = static_cast<SinkListCtx *>(userdata);
|
||||
if (info && ctx->out) {
|
||||
AudioOutputDevice d;
|
||||
d.sink = info->name ? info->name : "";
|
||||
d.description = info->description ? info->description : d.sink;
|
||||
ctx->out->push_back(d);
|
||||
}
|
||||
if (ctx->ml) pa_threaded_mainloop_signal(ctx->ml, 0);
|
||||
}
|
||||
|
||||
void serverInfoCb(pa_context * /*c*/, const pa_server_info * info, void * userdata)
|
||||
{
|
||||
auto * ctx = static_cast<SinkListCtx *>(userdata);
|
||||
if (info && info->default_sink_name && ctx->defaultSink) {
|
||||
*ctx->defaultSink = info->default_sink_name;
|
||||
}
|
||||
if (ctx->ml) pa_threaded_mainloop_signal(ctx->ml, 0);
|
||||
}
|
||||
|
||||
// 有界等待:避免任何情况下卡死
|
||||
void waitOp(pa_threaded_mainloop * ml, pa_operation * op)
|
||||
{
|
||||
for (int i = 0; i < 200 && pa_operation_get_state(op) == PA_OPERATION_RUNNING; ++i) {
|
||||
pa_threaded_mainloop_wait(ml);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<AudioOutputDevice> listOutputDevices(std::string * error)
|
||||
{
|
||||
std::vector<AudioOutputDevice> out;
|
||||
pa_threaded_mainloop * ml = pa_threaded_mainloop_new();
|
||||
if (!ml) { if (error) *error = "pa_threaded_mainloop_new 失败"; return out; }
|
||||
pa_context * ctx = pa_context_new(pa_threaded_mainloop_get_api(ml), "live-caption-list");
|
||||
if (!ctx) { pa_threaded_mainloop_free(ml); if (error) *error = "pa_context_new 失败"; return out; }
|
||||
pa_context_set_state_callback(ctx, [](pa_context * c, void * ud) {
|
||||
auto * m = static_cast<pa_threaded_mainloop *>(ud);
|
||||
const pa_context_state_t st = pa_context_get_state(c);
|
||||
if (st == PA_CONTEXT_READY || st == PA_CONTEXT_FAILED || st == PA_CONTEXT_TERMINATED)
|
||||
pa_threaded_mainloop_signal(m, 0);
|
||||
}, ml);
|
||||
|
||||
pa_threaded_mainloop_start(ml);
|
||||
pa_threaded_mainloop_lock(ml);
|
||||
if (pa_context_connect(ctx, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) {
|
||||
pa_threaded_mainloop_unlock(ml);
|
||||
pa_context_unref(ctx); pa_threaded_mainloop_stop(ml); pa_threaded_mainloop_free(ml);
|
||||
if (error) *error = "连接 PulseAudio/PipeWire 失败";
|
||||
return out;
|
||||
}
|
||||
for (;;) {
|
||||
const pa_context_state_t st = pa_context_get_state(ctx);
|
||||
if (st == PA_CONTEXT_READY) break;
|
||||
if (!PA_CONTEXT_IS_GOOD(st)) {
|
||||
pa_threaded_mainloop_unlock(ml);
|
||||
pa_context_unref(ctx); pa_threaded_mainloop_stop(ml); pa_threaded_mainloop_free(ml);
|
||||
if (error) *error = "无法连接到音频服务";
|
||||
return out;
|
||||
}
|
||||
pa_threaded_mainloop_wait(ml);
|
||||
}
|
||||
|
||||
std::string defaultSink;
|
||||
SinkListCtx lctx{&out, &defaultSink, ml};
|
||||
|
||||
pa_operation * opDefault = pa_context_get_server_info(ctx, serverInfoCb, &lctx);
|
||||
waitOp(ml, opDefault);
|
||||
pa_operation_unref(opDefault);
|
||||
|
||||
pa_operation * opSinks = pa_context_get_sink_info_list(ctx, sinkInfoCb, &lctx);
|
||||
waitOp(ml, opSinks);
|
||||
pa_operation_unref(opSinks);
|
||||
|
||||
for (auto & d : out) d.isDefault = (d.sink == defaultSink);
|
||||
|
||||
pa_context_disconnect(ctx);
|
||||
pa_context_unref(ctx);
|
||||
pa_threaded_mainloop_unlock(ml);
|
||||
pa_threaded_mainloop_stop(ml);
|
||||
pa_threaded_mainloop_free(ml);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 实时采集:某个输出设备的 monitor(默认跟随系统默认输出)
|
||||
// ---------------------------------------------------------------------------
|
||||
struct MonitorCapture::Impl {
|
||||
pa_threaded_mainloop * ml = nullptr;
|
||||
@@ -250,7 +349,8 @@ MonitorCapture::~MonitorCapture()
|
||||
|
||||
std::string MonitorCapture::deviceName() const { return d->deviceName; }
|
||||
|
||||
bool MonitorCapture::start(int targetRate, ChunkCallback callback, std::string * error)
|
||||
bool MonitorCapture::start(int targetRate, ChunkCallback callback, std::string * error,
|
||||
const std::string & device)
|
||||
{
|
||||
const auto fail = [error](const std::string & m) {
|
||||
if (error) *error = m;
|
||||
@@ -288,17 +388,21 @@ bool MonitorCapture::start(int targetRate, ChunkCallback callback, std::string *
|
||||
pa_threaded_mainloop_wait(d->ml);
|
||||
}
|
||||
|
||||
// 查默认 sink,拼出它的 monitor 源
|
||||
d->deviceName.clear();
|
||||
pa_operation * op = pa_context_get_server_info(d->ctx, storeMonitor, d);
|
||||
while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) {
|
||||
pa_threaded_mainloop_wait(d->ml);
|
||||
}
|
||||
pa_operation_unref(op);
|
||||
|
||||
if (d->deviceName.empty()) {
|
||||
pa_threaded_mainloop_unlock(d->ml);
|
||||
return fail("拿不到默认输出设备名");
|
||||
if (device.empty()) {
|
||||
// 跟随系统默认输出
|
||||
d->deviceName.clear();
|
||||
pa_operation * op = pa_context_get_server_info(d->ctx, storeMonitor, d);
|
||||
while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) {
|
||||
pa_threaded_mainloop_wait(d->ml);
|
||||
}
|
||||
pa_operation_unref(op);
|
||||
if (d->deviceName.empty()) {
|
||||
pa_threaded_mainloop_unlock(d->ml);
|
||||
return fail("拿不到默认输出设备名");
|
||||
}
|
||||
} else {
|
||||
// 指定设备(sink 名)
|
||||
d->deviceName = device + ".monitor";
|
||||
}
|
||||
|
||||
// 以设备实际速率请求(默认 48k)
|
||||
@@ -7,6 +7,16 @@
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 一个可选的采集源(输出设备的 monitor)
|
||||
struct AudioOutputDevice {
|
||||
std::string sink; // 设备名
|
||||
std::string description; // 人类可读描述
|
||||
bool isDefault = false;
|
||||
};
|
||||
|
||||
// 列出所有输出设备(供设置界面选择采集源)
|
||||
std::vector<AudioOutputDevice> listOutputDevices(std::string * error = nullptr);
|
||||
|
||||
// 读取 WAV(PCM 16/24/32 位或 float32),降混为单声道并重采样到 targetRate。
|
||||
bool readWavMono(const std::string & path, int targetRate,
|
||||
std::vector<float> & out, std::string * error);
|
||||
@@ -23,7 +33,9 @@ public:
|
||||
MonitorCapture(const MonitorCapture &) = delete;
|
||||
MonitorCapture & operator=(const MonitorCapture &) = delete;
|
||||
|
||||
bool start(int targetRate, ChunkCallback callback, std::string * error);
|
||||
// device: 空 = 跟随系统默认输出;否则是 sink 名(见 listOutputDevices)
|
||||
bool start(int targetRate, ChunkCallback callback, std::string * error,
|
||||
const std::string & device = std::string());
|
||||
void stop();
|
||||
|
||||
// 实际采集的 monitor 源名(start 成功后有效)
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
|
||||
#include "transcript.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 一次整段转写的结果
|
||||
struct AsrResult {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
ParsedTranscript transcript; // 已拆出 language / text
|
||||
std::string raw; // 模型原始输出(未 trim)
|
||||
double inferSeconds = 0.0;
|
||||
int tokenCount = 0;
|
||||
};
|
||||
|
||||
// 流式单步的结果
|
||||
struct AsrStreamStep {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
std::string newText; // 本步新生成的文本(不含前缀,未 trim)
|
||||
int newTokens = 0;
|
||||
int audioTokens = 0;
|
||||
double encodeSeconds = 0.0; // 音频编码 + 写入 KV
|
||||
double prefillSeconds = 0.0; // 文本前缀(tail + prefix)prefill
|
||||
double genSeconds = 0.0; // 贪心生成
|
||||
double inferSeconds = 0.0; // 以上合计
|
||||
};
|
||||
|
||||
// 推理后端的种类,决定上层用哪条流式路径
|
||||
enum class AsrKind {
|
||||
PrefixRollback, // 离线模型 + 前缀回滚(Qwen3-ASR / llama.cpp)
|
||||
NativeStreaming, // 有状态流式识别器(sherpa-onnx 的 transducer 系)
|
||||
};
|
||||
|
||||
// 把推理后端抽象出来,好处是流式策略(StreamingAsr)和实时管线(LivePipeline)
|
||||
// 可以用一个假的实现来测,不必加载真模型。
|
||||
class IAsr {
|
||||
public:
|
||||
virtual ~IAsr() = default;
|
||||
|
||||
virtual AsrKind kind() const { return AsrKind::PrefixRollback; }
|
||||
|
||||
// 期望的输入采样率(Qwen3-ASR 为 16000)
|
||||
virtual int sampleRate() const = 0;
|
||||
|
||||
// ---- NativeStreaming 专用 ----
|
||||
// 喂入音频,返回"这一句到目前为止"的完整文本(识别器会随时修正前面的词)
|
||||
virtual std::string streamFeed(const float * /*pcm*/, size_t /*n*/) { return {}; }
|
||||
// 结束这一句(把尾部 flush 出来),返回最终文本
|
||||
virtual std::string streamFinish() { return {}; }
|
||||
|
||||
// 整段转写:把 prefix 当作"已经生成的 assistant 文本",从那里继续生成
|
||||
virtual AsrResult transcribeWithPrefix(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix) = 0;
|
||||
|
||||
// 流式:只编码新音频,已解码的音频留在 KV cache 里复用
|
||||
virtual AsrStreamStep streamAppend(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix, int maxTokens) = 0;
|
||||
|
||||
// 追加式轮次(append-only):把这一小段音频当作一个新的对话轮,
|
||||
// 追加到已有 KV 的末尾,不重算任何前缀、也不重编码旧音频。
|
||||
// 代价是每块只用自己的长度做编码(没有 8s 上下文),准确率需要实测确认。
|
||||
virtual AsrStreamStep streamAppendTurn(const float * pcm, size_t nSamples,
|
||||
int maxTokens) = 0;
|
||||
|
||||
virtual void streamReset() = 0;
|
||||
|
||||
// 用词表把 text 编码成 token、丢掉最后 dropLast 个、再还原成文本。
|
||||
// 对应官方的 unfixed_token_num 回滚。
|
||||
virtual std::string dropLastTokens(const std::string & text, int dropLast) const = 0;
|
||||
|
||||
// 便利:不带前缀的整段转写
|
||||
AsrResult transcribe(const float * pcm, size_t nSamples)
|
||||
{
|
||||
return transcribeWithPrefix(pcm, nSamples, std::string());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "livepipeline.h"
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace {
|
||||
constexpr int kFrameSamples = 320; // 20ms @16k
|
||||
} // namespace
|
||||
|
||||
LivePipeline::LivePipeline(IAsr & asr, LivePipelineOptions opt)
|
||||
: asr_(asr), opt_(std::move(opt)), stream_(asr, opt_.stream) {}
|
||||
|
||||
LivePipeline::~LivePipeline()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
std::string LivePipeline::deviceName() const
|
||||
{
|
||||
return capture_.deviceName();
|
||||
}
|
||||
|
||||
bool LivePipeline::start(std::string * error)
|
||||
{
|
||||
const bool ok = capture_.start(
|
||||
asr_.sampleRate(),
|
||||
[this](const float * s, size_t n) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
pending_.insert(pending_.end(), s, s + n);
|
||||
}
|
||||
cv_.notify_one();
|
||||
},
|
||||
error,
|
||||
opt_.captureDevice);
|
||||
if (!ok) return false;
|
||||
|
||||
worker_ = std::thread([this] { workerLoop(); });
|
||||
return true;
|
||||
}
|
||||
|
||||
void LivePipeline::stop()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
quit_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
if (worker_.joinable()) worker_.join();
|
||||
capture_.stop();
|
||||
}
|
||||
|
||||
void LivePipeline::workerLoop()
|
||||
{
|
||||
for (;;) {
|
||||
std::vector<float> chunk;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(mutex_);
|
||||
cv_.wait_for(lk, std::chrono::milliseconds(50),
|
||||
[this] { return quit_ || !pending_.empty(); });
|
||||
if (quit_ && pending_.empty()) break;
|
||||
chunk.swap(pending_);
|
||||
}
|
||||
if (!chunk.empty()) process(chunk.data(), chunk.size());
|
||||
}
|
||||
|
||||
if (inSegment_) finishSegment();
|
||||
}
|
||||
|
||||
void LivePipeline::emitStep(const StreamingAsr::Step & s)
|
||||
{
|
||||
if (!s.ok || !onCaption_) return;
|
||||
onCaption_(s.committed, s.tail, s.language);
|
||||
}
|
||||
|
||||
void LivePipeline::process(const float * pcm, size_t n)
|
||||
{
|
||||
buffer_.insert(buffer_.end(), pcm, pcm + n);
|
||||
|
||||
const size_t prerollSamples = (size_t) (opt_.prerollSec * asr_.sampleRate());
|
||||
const float frameSec = (float) kFrameSamples / asr_.sampleRate();
|
||||
|
||||
std::vector<float> segAudio; // 本段要送进引擎的音频
|
||||
bool flushNow = false;
|
||||
|
||||
size_t off = 0;
|
||||
for (; off + kFrameSamples <= buffer_.size(); off += kFrameSamples) {
|
||||
const float * frame = buffer_.data() + off;
|
||||
const bool speech = vad_.feed(frame, kFrameSamples);
|
||||
|
||||
if (!inSegment_) {
|
||||
// 静音期间什么都不送给模型:否则模型会对静音产生幻觉
|
||||
if (speech) {
|
||||
inSegment_ = true;
|
||||
silenceAcc_ = 0.0f;
|
||||
segAudio.insert(segAudio.end(), preroll_.begin(), preroll_.end());
|
||||
preroll_.clear();
|
||||
segAudio.insert(segAudio.end(), frame, frame + kFrameSamples);
|
||||
} else {
|
||||
preroll_.insert(preroll_.end(), frame, frame + kFrameSamples);
|
||||
if (preroll_.size() > prerollSamples) {
|
||||
preroll_.erase(preroll_.begin(),
|
||||
preroll_.begin() + (long) (preroll_.size() - prerollSamples));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
segAudio.insert(segAudio.end(), frame, frame + kFrameSamples);
|
||||
if (speech) silenceAcc_ = 0.0f;
|
||||
else silenceAcc_ += frameSec;
|
||||
|
||||
if (silenceAcc_ >= (float) opt_.silenceTimeoutSec) {
|
||||
flushNow = true;
|
||||
off += kFrameSamples; // 这一帧已经并入 segAudio
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!segAudio.empty()) {
|
||||
const auto cb = [this](const StreamingAsr::Step & s) { emitStep(s); };
|
||||
stream_.feed(segAudio.data(), segAudio.size(), cb);
|
||||
}
|
||||
|
||||
if (flushNow) {
|
||||
const auto cb = [this](const StreamingAsr::Step & s) { emitStep(s); };
|
||||
stream_.flush(cb);
|
||||
stream_.reset();
|
||||
inSegment_ = false;
|
||||
silenceAcc_ = 0.0f;
|
||||
preroll_.clear();
|
||||
}
|
||||
|
||||
if (off > 0) buffer_.erase(buffer_.begin(), buffer_.begin() + (long) off);
|
||||
}
|
||||
|
||||
void LivePipeline::finishSegment()
|
||||
{
|
||||
if (!inSegment_) return;
|
||||
const auto cb = [this](const StreamingAsr::Step & s) { emitStep(s); };
|
||||
stream_.flush(cb);
|
||||
stream_.reset();
|
||||
inSegment_ = false;
|
||||
silenceAcc_ = 0.0f;
|
||||
preroll_.clear();
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "audio.h"
|
||||
#include "iasr.h"
|
||||
#include "streamingasr.h"
|
||||
#include "vad.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
struct LivePipelineOptions {
|
||||
StreamOptions stream;
|
||||
std::string captureDevice; // 空 = 跟随系统默认输出;否则是 sink 名
|
||||
double silenceTimeoutSec = 0.8; // 静音多久算一句结束
|
||||
double prerollSec = 0.25; // 语音开始前保留的一段,避免吃掉词头
|
||||
};
|
||||
|
||||
// 实时管线:采集 → VAD → 分段 → 流式转写。
|
||||
//
|
||||
// 刻意不带任何 Qt 依赖(回调用 std::function),好处是可以脱离 UI 单独测试:
|
||||
// 测试直接调 process() 喂音频,不必碰 PulseAudio,也不用跑事件循环。
|
||||
class LivePipeline {
|
||||
public:
|
||||
using CaptionCallback = std::function<void(const std::string & committed,
|
||||
const std::string & tail,
|
||||
const std::string & language)>;
|
||||
using ErrorCallback = std::function<void(const std::string & message)>;
|
||||
|
||||
LivePipeline(IAsr & asr, LivePipelineOptions opt = {});
|
||||
~LivePipeline();
|
||||
|
||||
LivePipeline(const LivePipeline &) = delete;
|
||||
LivePipeline & operator=(const LivePipeline &) = delete;
|
||||
|
||||
void setCaptionCallback(CaptionCallback cb) { onCaption_ = std::move(cb); }
|
||||
void setErrorCallback(ErrorCallback cb) { onError_ = std::move(cb); }
|
||||
|
||||
// 启动真实采集(默认输出设备的 monitor)
|
||||
bool start(std::string * error = nullptr);
|
||||
void stop();
|
||||
std::string deviceName() const;
|
||||
|
||||
// 同步处理一段 16k 单声道音频。
|
||||
// 真实运行时由采集线程调用;测试可以直接调它。
|
||||
void process(const float * pcm, size_t n);
|
||||
|
||||
// 结束当前这一段并提交(流结束或手动收尾时用)
|
||||
void finishSegment();
|
||||
|
||||
// 注意:StreamingAsr::committedText() 是按值返回的,这里也必须按值返回
|
||||
std::string committedText() const { return stream_.committedText(); }
|
||||
const std::string & language() const { return stream_.language(); }
|
||||
int chunkCount() const { return stream_.chunkCount(); }
|
||||
bool inSegment() const { return inSegment_; }
|
||||
|
||||
private:
|
||||
void workerLoop();
|
||||
void emitStep(const StreamingAsr::Step & s);
|
||||
|
||||
IAsr & asr_;
|
||||
LivePipelineOptions opt_;
|
||||
Vad vad_;
|
||||
StreamingAsr stream_;
|
||||
|
||||
CaptionCallback onCaption_;
|
||||
ErrorCallback onError_;
|
||||
|
||||
bool inSegment_ = false;
|
||||
float silenceAcc_ = 0.0f;
|
||||
std::vector<float> preroll_; // 语音开始前保留的一小段
|
||||
std::vector<float> buffer_; // 跨批次的残留样本(不接上会持续丢样本)
|
||||
|
||||
MonitorCapture capture_;
|
||||
std::thread worker_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<float> pending_;
|
||||
bool quit_ = false;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,638 @@
|
||||
#include "qwen3asr.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
#include <llama.h>
|
||||
#include <mtmd.h>
|
||||
#include <mtmd-helper.h>
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string defaultQwenChatPrompt(const std::string & content)
|
||||
{
|
||||
// Qwen3-ASR 的 chat template 就是标准 ChatML(见模型 GGUF 的 tokenizer.chat_template)
|
||||
return "<|im_start|>user\n" + content + "<|im_end|>\n<|im_start|>assistant\n";
|
||||
}
|
||||
|
||||
void silentLog(ggml_log_level /*level*/, const char * /*text*/, void * /*user*/) {}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct Qwen3Asr::Impl {
|
||||
AsrOptions opt;
|
||||
llama_model * model = nullptr;
|
||||
llama_context * ctx = nullptr;
|
||||
mtmd_context * mctx = nullptr;
|
||||
const llama_vocab * vocab = nullptr;
|
||||
int audioRate = 16000;
|
||||
|
||||
// 流式(增量)状态
|
||||
bool streamReady = false;
|
||||
std::vector<llama_token> headTokens; // 音频之前的 prompt 文本
|
||||
std::vector<llama_token> tailTokens; // 音频之后的 prompt 文本(含 assistant 头)
|
||||
std::vector<float> streamAudio; // 当前这段的全部音频(不滑动)
|
||||
size_t stableSamples = 0; // 已固化进 KV 的音频样本数(8s 对齐)
|
||||
llama_pos nPastStable = 0; // stable 音频末尾的 KV 位置
|
||||
|
||||
// 追加式轮次(append-only)状态
|
||||
bool turnReady = false;
|
||||
std::vector<llama_token> firstHead; // 第 1 轮的轮首文本(含 <|audio_start|>)
|
||||
std::vector<llama_token> contHead; // 后续轮的轮首文本(<|im_end|>\n<|im_start|>user\n<|audio_start|>)
|
||||
llama_pos nPastTurn = 0;
|
||||
int turnCount = 0;
|
||||
|
||||
std::string buildPrompt(const std::string & marker) const
|
||||
{
|
||||
const char * tmpl = llama_model_chat_template(model, nullptr);
|
||||
if (tmpl) {
|
||||
llama_chat_message msg{"user", marker.c_str()};
|
||||
std::vector<char> buf(marker.size() * 2 + 4096);
|
||||
const int32_t n = llama_chat_apply_template(tmpl, &msg, 1, true, buf.data(), (int32_t) buf.size());
|
||||
if (n > 0 && (size_t) n <= buf.size()) {
|
||||
return std::string(buf.data(), (size_t) n);
|
||||
}
|
||||
}
|
||||
return defaultQwenChatPrompt(marker);
|
||||
}
|
||||
|
||||
// 用显式位置解码一批 token(便于在增量流式里精确控制位置)
|
||||
bool decodeTokens(const llama_token * tokens, int32_t n, llama_pos startPos, bool wantLogits)
|
||||
{
|
||||
if (n <= 0) return true;
|
||||
llama_batch b = llama_batch_init(n, 0, 1);
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
b.token[i] = tokens[i];
|
||||
b.pos[i] = startPos + i;
|
||||
b.n_seq_id[i] = 1;
|
||||
b.seq_id[i][0] = 0;
|
||||
b.logits[i] = (wantLogits && i == n - 1) ? 1 : 0;
|
||||
}
|
||||
b.n_tokens = n;
|
||||
const int32_t rc = llama_decode(ctx, b);
|
||||
llama_batch_free(b);
|
||||
return rc == 0;
|
||||
}
|
||||
|
||||
// 把一段音频编码后追加到 KV 的 nPast 处
|
||||
bool appendAudio(const float * pcm, size_t nSamples, llama_pos & nPast, std::string * err)
|
||||
{
|
||||
if (nSamples == 0) return true;
|
||||
|
||||
mtmd_bitmap * bmp = mtmd_bitmap_init_from_audio(nSamples, pcm);
|
||||
if (!bmp) { if (err) *err = "构造音频 bitmap 失败"; return false; }
|
||||
|
||||
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
|
||||
const std::string marker = mtmd_default_marker();
|
||||
const mtmd_input_text itext{ marker.c_str(), false, true };
|
||||
const mtmd_bitmap * bms[1] = { bmp };
|
||||
|
||||
if (mtmd_tokenize(mctx, chunks, &itext, bms, 1) != 0) {
|
||||
mtmd_bitmap_free(bmp);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
if (err) *err = "音频 mtmd_tokenize 失败";
|
||||
return false;
|
||||
}
|
||||
|
||||
const mtmd_input_chunk * audioChunk = nullptr;
|
||||
for (size_t i = 0; i < mtmd_input_chunks_size(chunks); ++i) {
|
||||
const mtmd_input_chunk * c = mtmd_input_chunks_get(chunks, i);
|
||||
if (mtmd_input_chunk_get_type(c) == MTMD_INPUT_CHUNK_TYPE_AUDIO) { audioChunk = c; break; }
|
||||
}
|
||||
if (!audioChunk) {
|
||||
mtmd_bitmap_free(bmp);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
if (err) *err = "tokenize 结果里没有音频块";
|
||||
return false;
|
||||
}
|
||||
|
||||
llama_pos np = nPast;
|
||||
const int32_t rc = mtmd_helper_eval_chunk_single(mctx, ctx, audioChunk, nPast, /*seq_id*/ 0,
|
||||
opt.nBatch, /*logits_last*/ false, &np);
|
||||
mtmd_bitmap_free(bmp);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
if (rc != 0) { if (err) *err = "音频编码/解码失败"; return false; }
|
||||
|
||||
nPast = np;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 把带 media marker 的 prompt 拆成「音频前文本」和「音频后文本」两组 token
|
||||
bool splitPrompt(const std::string & skeleton,
|
||||
std::vector<llama_token> & head,
|
||||
std::vector<llama_token> & tail,
|
||||
std::string * err)
|
||||
{
|
||||
std::vector<float> dummy(1600, 0.0f); // 0.1s 占位,只为触发音频分块
|
||||
mtmd_bitmap * bmp = mtmd_bitmap_init_from_audio(dummy.size(), dummy.data());
|
||||
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
|
||||
const mtmd_input_text itext{ skeleton.c_str(), true, true };
|
||||
const mtmd_bitmap * bms[1] = { bmp };
|
||||
|
||||
if (mtmd_tokenize(mctx, chunks, &itext, bms, 1) != 0) {
|
||||
mtmd_bitmap_free(bmp);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
if (err) *err = "mtmd_tokenize 失败";
|
||||
return false;
|
||||
}
|
||||
mtmd_bitmap_free(bmp);
|
||||
|
||||
bool seenAudio = false;
|
||||
for (size_t i = 0; i < mtmd_input_chunks_size(chunks); ++i) {
|
||||
const mtmd_input_chunk * c = mtmd_input_chunks_get(chunks, i);
|
||||
if (mtmd_input_chunk_get_type(c) == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
|
||||
seenAudio = true;
|
||||
continue;
|
||||
}
|
||||
size_t n = 0;
|
||||
const llama_token * toks = mtmd_input_chunk_get_tokens_text(c, &n);
|
||||
if (!toks || n == 0) continue;
|
||||
std::vector<llama_token> & dst = seenAudio ? tail : head;
|
||||
dst.insert(dst.end(), toks, toks + n);
|
||||
}
|
||||
mtmd_input_chunks_free(chunks);
|
||||
|
||||
if (head.empty()) {
|
||||
if (err) *err = "prompt 里没有音频之前的文本";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
Qwen3Asr::Qwen3Asr() : d(new Impl) {}
|
||||
|
||||
Qwen3Asr::~Qwen3Asr()
|
||||
{
|
||||
if (!d) return;
|
||||
if (d->mctx) mtmd_free(d->mctx);
|
||||
if (d->ctx) llama_free(d->ctx);
|
||||
if (d->model) llama_model_free(d->model);
|
||||
delete d;
|
||||
}
|
||||
|
||||
int Qwen3Asr::sampleRate() const { return d->audioRate; }
|
||||
|
||||
bool Qwen3Asr::load(const AsrOptions & opt, std::string * error)
|
||||
{
|
||||
const auto fail = [error](const std::string & msg) {
|
||||
if (error) *error = msg;
|
||||
return false;
|
||||
};
|
||||
|
||||
d->opt = opt;
|
||||
|
||||
if (!opt.verbose) {
|
||||
llama_log_set(silentLog, nullptr);
|
||||
mtmd_log_set(silentLog, nullptr);
|
||||
}
|
||||
|
||||
llama_backend_init();
|
||||
|
||||
llama_model_params mparams = llama_model_default_params();
|
||||
mparams.n_gpu_layers = 0; // 本机无独显,强制 CPU
|
||||
mparams.use_mmap = true;
|
||||
|
||||
d->model = llama_model_load_from_file(opt.modelPath.c_str(), mparams);
|
||||
if (!d->model) {
|
||||
return fail("加载主模型失败: " + opt.modelPath);
|
||||
}
|
||||
d->vocab = llama_model_get_vocab(d->model);
|
||||
|
||||
llama_context_params cparams = llama_context_default_params();
|
||||
cparams.n_ctx = (uint32_t) opt.nCtx;
|
||||
cparams.n_batch = (uint32_t) opt.nBatch;
|
||||
cparams.n_ubatch = (uint32_t) opt.nUbatch;
|
||||
cparams.n_threads = opt.threads;
|
||||
cparams.n_threads_batch = opt.threads;
|
||||
|
||||
d->ctx = llama_init_from_model(d->model, cparams);
|
||||
if (!d->ctx) {
|
||||
return fail("创建 llama 上下文失败");
|
||||
}
|
||||
|
||||
mtmd_context_params mctxParams = mtmd_context_params_default();
|
||||
mctxParams.use_gpu = false;
|
||||
mctxParams.n_threads = opt.threads;
|
||||
mctxParams.print_timings = false;
|
||||
mctxParams.warmup = opt.warmup;
|
||||
|
||||
d->mctx = mtmd_init_from_file(opt.mmprojPath.c_str(), d->model, mctxParams);
|
||||
if (!d->mctx) {
|
||||
return fail("加载 mmproj 失败: " + opt.mmprojPath);
|
||||
}
|
||||
|
||||
if (!mtmd_support_audio(d->mctx)) {
|
||||
return fail("该 mmproj 不支持音频输入(需要 clip.projector_type = qwen3a 的版本)");
|
||||
}
|
||||
|
||||
const int rate = mtmd_get_audio_sample_rate(d->mctx);
|
||||
if (rate > 0) d->audioRate = rate;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Qwen3Asr::dropLastTokens(const std::string & text, int dropLast) const
|
||||
{
|
||||
if (!d->vocab || dropLast <= 0 || text.empty()) return text;
|
||||
|
||||
std::vector<llama_token> tokens(text.size() + 16);
|
||||
int32_t n = llama_tokenize(d->vocab, text.c_str(), (int32_t) text.size(),
|
||||
tokens.data(), (int32_t) tokens.size(),
|
||||
/*add_special*/ false, /*parse_special*/ true);
|
||||
if (n < 0) { // 缓冲区不够,按返回的所需长度重来
|
||||
tokens.resize((size_t) -n);
|
||||
n = llama_tokenize(d->vocab, text.c_str(), (int32_t) text.size(),
|
||||
tokens.data(), (int32_t) tokens.size(), false, true);
|
||||
if (n < 0) return text;
|
||||
}
|
||||
tokens.resize((size_t) n);
|
||||
if ((int) tokens.size() <= dropLast) return {};
|
||||
|
||||
tokens.resize(tokens.size() - (size_t) dropLast);
|
||||
|
||||
// special=true:让 <asr_text> 这类特殊标记以字面形式保留,前缀才能原样回喂
|
||||
std::string out;
|
||||
char buf[512];
|
||||
for (llama_token id : tokens) {
|
||||
const int32_t m = llama_token_to_piece(d->vocab, id, buf, sizeof(buf), 0, /*special*/ true);
|
||||
if (m > 0) out.append(buf, (size_t) m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
AsrResult Qwen3Asr::transcribeWithPrefix(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix)
|
||||
{
|
||||
AsrResult res;
|
||||
|
||||
if (!d->model || !d->ctx || !d->mctx) {
|
||||
res.error = "模型未加载";
|
||||
return res;
|
||||
}
|
||||
if (nSamples == 0) {
|
||||
res.error = "音频为空";
|
||||
return res;
|
||||
}
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
// 每段独立转写,先清空 KV cache
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
|
||||
const std::string marker = mtmd_default_marker();
|
||||
// 关键:assistant 头之后接上"已生成文本",让模型从那里继续生成(前缀回滚)
|
||||
const std::string prompt = d->buildPrompt(marker) + prefix;
|
||||
|
||||
mtmd_bitmap * bitmap = mtmd_bitmap_init_from_audio(nSamples, pcm);
|
||||
if (!bitmap) {
|
||||
res.error = "构造音频 bitmap 失败";
|
||||
return res;
|
||||
}
|
||||
|
||||
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
|
||||
const mtmd_input_text text{ prompt.c_str(), /*add_special*/ true, /*parse_special*/ true };
|
||||
const mtmd_bitmap * bitmaps[1] = { bitmap };
|
||||
|
||||
const int32_t tokRes = mtmd_tokenize(d->mctx, chunks, &text, bitmaps, 1);
|
||||
if (tokRes != 0) {
|
||||
mtmd_bitmap_free(bitmap);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
res.error = "mtmd_tokenize 失败 (code " + std::to_string(tokRes) + ")";
|
||||
return res;
|
||||
}
|
||||
|
||||
llama_pos nPast = 0;
|
||||
const int32_t evalRes = mtmd_helper_eval_chunks(
|
||||
d->mctx, d->ctx, chunks,
|
||||
/*n_past*/ 0, /*seq_id*/ 0, /*n_batch*/ d->opt.nBatch,
|
||||
/*logits_last*/ true, &nPast);
|
||||
mtmd_bitmap_free(bitmap);
|
||||
if (evalRes != 0) {
|
||||
mtmd_input_chunks_free(chunks);
|
||||
res.error = "mtmd_helper_eval_chunks 失败 (code " + std::to_string(evalRes) + ")";
|
||||
return res;
|
||||
}
|
||||
mtmd_input_chunks_free(chunks);
|
||||
|
||||
// 贪心解码
|
||||
llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
|
||||
llama_sampler_chain_add(smpl, llama_sampler_init_greedy());
|
||||
|
||||
std::string out;
|
||||
for (int i = 0; i < d->opt.maxTokens; ++i) {
|
||||
llama_token id = llama_sampler_sample(smpl, d->ctx, -1);
|
||||
if (llama_vocab_is_eog(d->vocab, id)) break;
|
||||
|
||||
char buf[256];
|
||||
const int32_t n = llama_token_to_piece(d->vocab, id, buf, sizeof(buf), 0, /*special*/ true);
|
||||
if (n > 0) out.append(buf, (size_t) n);
|
||||
++res.tokenCount;
|
||||
|
||||
llama_batch batch = llama_batch_get_one(&id, 1);
|
||||
if (llama_decode(d->ctx, batch) != 0) {
|
||||
res.error = "llama_decode 失败";
|
||||
break;
|
||||
}
|
||||
}
|
||||
llama_sampler_free(smpl);
|
||||
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
res.inferSeconds = std::chrono::duration<double>(t1 - t0).count();
|
||||
res.raw = out;
|
||||
res.transcript = parseAsrOutput(out);
|
||||
res.ok = res.error.empty();
|
||||
return res;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 流式(增量 KV 复用)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
void Qwen3Asr::streamReset()
|
||||
{
|
||||
if (!d->ctx) return;
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
d->streamReady = false;
|
||||
d->headTokens.clear();
|
||||
d->tailTokens.clear();
|
||||
d->streamAudio.clear();
|
||||
d->stableSamples = 0;
|
||||
d->nPastStable = 0;
|
||||
|
||||
d->turnReady = false;
|
||||
d->firstHead.clear();
|
||||
d->contHead.clear();
|
||||
d->nPastTurn = 0;
|
||||
d->turnCount = 0;
|
||||
}
|
||||
|
||||
// 追加式:把音频切成定长段,每段独立转写后按顺序拼接(sglang 的 segment 模式)。
|
||||
// 好处是纯追加/独立:不重算前缀、不重编码旧音频,单步成本与总长无关。
|
||||
// 注意:段长必须给足(约 8s),因为编码器需要它的 8s 注意力窗口。
|
||||
bool Qwen3Asr::prepareTurn(std::string * error)
|
||||
{
|
||||
if (d->turnReady) return true;
|
||||
|
||||
const std::string marker = mtmd_default_marker();
|
||||
const std::string s1 = "<|im_start|>user\n" + marker +
|
||||
"<|im_end|>\n<|im_start|>assistant\n";
|
||||
|
||||
std::vector<llama_token> tail1;
|
||||
if (!d->splitPrompt(s1, d->firstHead, tail1, error)) return false;
|
||||
d->tailTokens = tail1;
|
||||
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
d->nPastTurn = 0;
|
||||
d->turnCount = 0;
|
||||
d->turnReady = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
AsrStreamStep Qwen3Asr::streamAppendTurn(const float * pcm, size_t nSamples, int maxTokens)
|
||||
{
|
||||
AsrStreamStep res;
|
||||
if (!d->model || !d->ctx || !d->mctx) { res.error = "模型未加载"; return res; }
|
||||
if (nSamples == 0) { res.error = "音频为空"; return res; }
|
||||
|
||||
std::string err;
|
||||
if (!prepareTurn(&err)) { res.error = err; return res; }
|
||||
|
||||
// 每一轮都当作独立的一段来转写(清空 KV、只用第 1 轮的 prompt)。
|
||||
//
|
||||
// 不能沿用上一轮的上下文:实测模型会"抄"上一轮的文本 —— 新一轮的音频
|
||||
// 哪怕内容完全不同,它也会把上一轮的句子原样再吐一遍。
|
||||
// 这与 sglang 给 Qwen3-ASR 定的 segment 流式模式一致:
|
||||
// 把音频切成定长段分别独立转写,再按顺序拼接。
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
d->nPastTurn = 0;
|
||||
d->turnCount = 0;
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
// 1) 轮首文本(全新的一段,从位置 0 开始)
|
||||
const std::vector<llama_token> & head = d->firstHead;
|
||||
llama_pos p = d->nPastTurn;
|
||||
if (!d->decodeTokens(head.data(), (int32_t) head.size(), p, false)) {
|
||||
res.error = "解码轮首失败";
|
||||
return res;
|
||||
}
|
||||
p += (llama_pos) head.size();
|
||||
|
||||
// 2) 这一小段音频:只编码一次,写进 KV 就永久保留
|
||||
const llama_pos beforeAudio = p;
|
||||
if (!d->appendAudio(pcm, nSamples, p, &err)) {
|
||||
res.error = "音频编码/解码失败: " + err;
|
||||
return res;
|
||||
}
|
||||
res.audioTokens = (int) (p - beforeAudio);
|
||||
const auto tEnc = std::chrono::steady_clock::now();
|
||||
|
||||
// 3) 轮尾文本 + 开始生成
|
||||
if (!d->decodeTokens(d->tailTokens.data(), (int32_t) d->tailTokens.size(), p, true)) {
|
||||
res.error = "解码轮尾失败";
|
||||
return res;
|
||||
}
|
||||
p += (llama_pos) d->tailTokens.size();
|
||||
|
||||
const auto tPre = std::chrono::steady_clock::now();
|
||||
|
||||
llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
|
||||
llama_sampler_chain_add(smpl, llama_sampler_init_greedy());
|
||||
|
||||
std::string out;
|
||||
for (int i = 0; i < maxTokens; ++i) {
|
||||
llama_token id = llama_sampler_sample(smpl, d->ctx, -1);
|
||||
if (llama_vocab_is_eog(d->vocab, id)) break;
|
||||
|
||||
char buf[256];
|
||||
const int32_t n = llama_token_to_piece(d->vocab, id, buf, sizeof(buf), 0, true);
|
||||
if (n > 0) out.append(buf, (size_t) n);
|
||||
++res.newTokens;
|
||||
|
||||
if (!d->decodeTokens(&id, 1, p, true)) { res.error = "生成时解码失败"; break; }
|
||||
++p;
|
||||
}
|
||||
llama_sampler_free(smpl);
|
||||
|
||||
d->nPastTurn = p;
|
||||
++d->turnCount;
|
||||
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
res.encodeSeconds = std::chrono::duration<double>(tEnc - t0).count();
|
||||
res.prefillSeconds = std::chrono::duration<double>(tPre - tEnc).count();
|
||||
res.genSeconds = std::chrono::duration<double>(t1 - tPre).count();
|
||||
res.inferSeconds = std::chrono::duration<double>(t1 - t0).count();
|
||||
res.newText = out;
|
||||
res.ok = res.error.empty();
|
||||
return res;
|
||||
}
|
||||
|
||||
bool Qwen3Asr::prepareStream(std::string * error)
|
||||
{
|
||||
if (d->streamReady) return true;
|
||||
|
||||
// 用一个占位音频 tokenize 一次,只为切出「音频之前」和「音频之后」的 prompt 文本 token。
|
||||
// 占位音频本身不会被解码。
|
||||
std::vector<float> dummy(1600, 0.0f); // 0.1s
|
||||
mtmd_bitmap * bmp = mtmd_bitmap_init_from_audio(dummy.size(), dummy.data());
|
||||
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
|
||||
|
||||
const std::string marker = mtmd_default_marker();
|
||||
const std::string prompt = d->buildPrompt(marker);
|
||||
const mtmd_input_text itext{ prompt.c_str(), true, true };
|
||||
const mtmd_bitmap * bms[1] = { bmp };
|
||||
|
||||
if (mtmd_tokenize(d->mctx, chunks, &itext, bms, 1) != 0) {
|
||||
mtmd_bitmap_free(bmp);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
if (error) *error = "prepareStream: mtmd_tokenize 失败";
|
||||
return false;
|
||||
}
|
||||
mtmd_bitmap_free(bmp);
|
||||
|
||||
bool seenAudio = false;
|
||||
for (size_t i = 0; i < mtmd_input_chunks_size(chunks); ++i) {
|
||||
const mtmd_input_chunk * c = mtmd_input_chunks_get(chunks, i);
|
||||
if (mtmd_input_chunk_get_type(c) == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
|
||||
seenAudio = true;
|
||||
continue;
|
||||
}
|
||||
size_t n = 0;
|
||||
const llama_token * toks = mtmd_input_chunk_get_tokens_text(c, &n);
|
||||
if (!toks || n == 0) continue;
|
||||
std::vector<llama_token> & dst = seenAudio ? d->tailTokens : d->headTokens;
|
||||
dst.insert(dst.end(), toks, toks + n);
|
||||
}
|
||||
mtmd_input_chunks_free(chunks);
|
||||
|
||||
if (d->headTokens.empty() || d->tailTokens.empty()) {
|
||||
if (error) *error = "prepareStream: 没能切出音频前后的 prompt 文本";
|
||||
return false;
|
||||
}
|
||||
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
if (!d->decodeTokens(d->headTokens.data(), (int32_t) d->headTokens.size(), 0, false)) {
|
||||
if (error) *error = "prepareStream: 解码 prompt 头部失败";
|
||||
return false;
|
||||
}
|
||||
d->nPastStable = (llama_pos) d->headTokens.size();
|
||||
d->streamReady = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 8 秒对齐的音频切片:这是编码器的注意力窗口(n_window_infer = 800 帧 @100Hz)。
|
||||
// 按这个粒度切,编码结果才和「整段音频一次编码」一致;切小了会明显掉准确率。
|
||||
static constexpr double kSliceSeconds = 8.0;
|
||||
|
||||
AsrStreamStep Qwen3Asr::streamAppend(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix, int maxTokens)
|
||||
{
|
||||
AsrStreamStep res;
|
||||
if (!d->model || !d->ctx || !d->mctx) { res.error = "模型未加载"; return res; }
|
||||
|
||||
std::string err;
|
||||
if (!prepareStream(&err)) { res.error = err; return res; }
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
d->streamAudio.insert(d->streamAudio.end(), pcm, pcm + nSamples);
|
||||
|
||||
const size_t sliceSamples = (size_t) (kSliceSeconds * d->audioRate);
|
||||
const size_t targetStable = (d->streamAudio.size() / sliceSamples) * sliceSamples;
|
||||
|
||||
const llama_pos nPastBefore = d->nPastStable;
|
||||
|
||||
// 1) 已排满 8s 的切片固化进 KV,之后永远复用
|
||||
if (targetStable > d->stableSamples) {
|
||||
llama_memory_seq_rm(llama_get_memory(d->ctx), 0, d->nPastStable, -1);
|
||||
llama_pos np = d->nPastStable;
|
||||
if (!d->appendAudio(d->streamAudio.data() + d->stableSamples,
|
||||
targetStable - d->stableSamples, np, &err)) {
|
||||
res.error = "固化音频切片失败: " + err;
|
||||
return res;
|
||||
}
|
||||
d->nPastStable = np;
|
||||
d->stableSamples = targetStable;
|
||||
}
|
||||
|
||||
// 2) 尾部不满 8s 的部分:每次重编码,但只是临时的(下一步会被丢掉)
|
||||
llama_memory_seq_rm(llama_get_memory(d->ctx), 0, d->nPastStable, -1);
|
||||
llama_pos nPast = d->nPastStable;
|
||||
if (d->streamAudio.size() > d->stableSamples) {
|
||||
if (!d->appendAudio(d->streamAudio.data() + d->stableSamples,
|
||||
d->streamAudio.size() - d->stableSamples, nPast, &err)) {
|
||||
res.error = "编码尾部音频失败: " + err;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
res.audioTokens = (int) (nPast - nPastBefore);
|
||||
const auto tEnc = std::chrono::steady_clock::now();
|
||||
|
||||
// 3) 音频之后的 prompt 文本 + 前缀
|
||||
std::vector<llama_token> prefixToks;
|
||||
if (!prefix.empty()) {
|
||||
prefixToks.resize(prefix.size() + 16);
|
||||
int32_t n = llama_tokenize(d->vocab, prefix.c_str(), (int32_t) prefix.size(),
|
||||
prefixToks.data(), (int32_t) prefixToks.size(),
|
||||
/*add_special*/ false, /*parse_special*/ true);
|
||||
if (n < 0) {
|
||||
prefixToks.resize((size_t) -n);
|
||||
n = llama_tokenize(d->vocab, prefix.c_str(), (int32_t) prefix.size(),
|
||||
prefixToks.data(), (int32_t) prefixToks.size(), false, true);
|
||||
}
|
||||
if (n < 0) { res.error = "前缀分词失败"; return res; }
|
||||
prefixToks.resize((size_t) n);
|
||||
}
|
||||
|
||||
llama_pos p = nPast;
|
||||
const bool prefixLast = prefixToks.empty();
|
||||
if (!d->decodeTokens(d->tailTokens.data(), (int32_t) d->tailTokens.size(), p, prefixLast)) {
|
||||
res.error = "解码 tail 失败";
|
||||
return res;
|
||||
}
|
||||
p += (llama_pos) d->tailTokens.size();
|
||||
|
||||
if (!prefixToks.empty()) {
|
||||
if (!d->decodeTokens(prefixToks.data(), (int32_t) prefixToks.size(), p, true)) {
|
||||
res.error = "解码前缀失败";
|
||||
return res;
|
||||
}
|
||||
p += (llama_pos) prefixToks.size();
|
||||
}
|
||||
|
||||
// 4) 贪心生成(每个 token 的 logits 都要留给下一次采样)
|
||||
llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
|
||||
llama_sampler_chain_add(smpl, llama_sampler_init_greedy());
|
||||
|
||||
const auto tPre = std::chrono::steady_clock::now();
|
||||
|
||||
std::string out;
|
||||
for (int i = 0; i < maxTokens; ++i) {
|
||||
llama_token id = llama_sampler_sample(smpl, d->ctx, -1);
|
||||
if (llama_vocab_is_eog(d->vocab, id)) break;
|
||||
|
||||
char buf[256];
|
||||
const int32_t n = llama_token_to_piece(d->vocab, id, buf, sizeof(buf), 0, /*special*/ true);
|
||||
if (n > 0) out.append(buf, (size_t) n);
|
||||
++res.newTokens;
|
||||
|
||||
if (!d->decodeTokens(&id, 1, p, true)) { res.error = "生成时解码失败"; break; }
|
||||
++p;
|
||||
}
|
||||
llama_sampler_free(smpl);
|
||||
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
res.encodeSeconds = std::chrono::duration<double>(tEnc - t0).count();
|
||||
res.prefillSeconds = std::chrono::duration<double>(tPre - tEnc).count();
|
||||
res.genSeconds = std::chrono::duration<double>(t1 - tPre).count();
|
||||
res.inferSeconds = std::chrono::duration<double>(t1 - t0).count();
|
||||
res.newText = out;
|
||||
res.ok = res.error.empty();
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "iasr.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
struct AsrOptions {
|
||||
std::string modelPath; // Qwen3-ASR 主模型 GGUF(架构须为 qwen3vl)
|
||||
std::string mmprojPath; // 音频编码器 mmproj GGUF(clip + qwen3a)
|
||||
int threads = 8;
|
||||
int nCtx = 4096;
|
||||
int nBatch = 4096;
|
||||
int nUbatch = 1024;
|
||||
int maxTokens = 256; // 单段最多生成多少 token
|
||||
bool warmup = false; // mtmd 初始化后是否跑一次预热编码
|
||||
bool verbose = false;
|
||||
};
|
||||
|
||||
// 进程内 Qwen3-ASR 推理(libllama + libmtmd)。
|
||||
// 模型常驻,可反复调用;每次整段转写会清空 KV cache。
|
||||
class Qwen3Asr : public IAsr {
|
||||
public:
|
||||
Qwen3Asr();
|
||||
~Qwen3Asr() override;
|
||||
|
||||
Qwen3Asr(const Qwen3Asr &) = delete;
|
||||
Qwen3Asr & operator=(const Qwen3Asr &) = delete;
|
||||
|
||||
bool load(const AsrOptions & opt, std::string * error);
|
||||
|
||||
// ---- IAsr ----
|
||||
int sampleRate() const override;
|
||||
|
||||
AsrResult transcribeWithPrefix(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix) override;
|
||||
|
||||
AsrStreamStep streamAppend(const float * pcm, size_t nSamples,
|
||||
const std::string & prefix, int maxTokens) override;
|
||||
AsrStreamStep streamAppendTurn(const float * pcm, size_t nSamples, int maxTokens) override;
|
||||
void streamReset() override;
|
||||
|
||||
std::string dropLastTokens(const std::string & text, int dropLast) const override;
|
||||
|
||||
private:
|
||||
bool prepareStream(std::string * error);
|
||||
bool prepareTurn(std::string * error);
|
||||
|
||||
struct Impl;
|
||||
Impl * d = nullptr;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,132 @@
|
||||
#include "sherpaasr.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "sherpa-onnx/c-api/c-api.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
struct SherpaAsr::Impl {
|
||||
Options opt;
|
||||
const SherpaOnnxOnlineRecognizer * rec = nullptr;
|
||||
const SherpaOnnxOnlineStream * stream = nullptr;
|
||||
|
||||
std::string resultText() const
|
||||
{
|
||||
if (!rec || !stream) return {};
|
||||
const SherpaOnnxOnlineRecognizerResult * r =
|
||||
SherpaOnnxGetOnlineStreamResult(rec, stream);
|
||||
if (!r) return {};
|
||||
std::string text = r->text ? r->text : "";
|
||||
SherpaOnnxDestroyOnlineRecognizerResult(r);
|
||||
return text;
|
||||
}
|
||||
|
||||
void drain()
|
||||
{
|
||||
while (rec && stream && SherpaOnnxIsOnlineStreamReady(rec, stream)) {
|
||||
SherpaOnnxDecodeOnlineStream(rec, stream);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SherpaAsr::SherpaAsr() : d(new Impl) {}
|
||||
|
||||
SherpaAsr::~SherpaAsr()
|
||||
{
|
||||
if (!d) return;
|
||||
if (d->stream) SherpaOnnxDestroyOnlineStream(d->stream);
|
||||
if (d->rec) SherpaOnnxDestroyOnlineRecognizer(d->rec);
|
||||
delete d;
|
||||
}
|
||||
|
||||
bool SherpaAsr::load(const Options & opt, std::string * error)
|
||||
{
|
||||
const auto fail = [error](const std::string & msg) {
|
||||
if (error) *error = msg;
|
||||
return false;
|
||||
};
|
||||
|
||||
d->opt = opt;
|
||||
|
||||
SherpaOnnxOnlineRecognizerConfig cfg;
|
||||
std::memset(&cfg, 0, sizeof(cfg));
|
||||
cfg.feat_config.sample_rate = 16000;
|
||||
cfg.feat_config.feature_dim = 80;
|
||||
cfg.model_config.transducer.encoder = opt.encoder.c_str();
|
||||
cfg.model_config.transducer.decoder = opt.decoder.c_str();
|
||||
cfg.model_config.transducer.joiner = opt.joiner.c_str();
|
||||
cfg.model_config.tokens = opt.tokens.c_str();
|
||||
cfg.model_config.num_threads = opt.threads;
|
||||
cfg.model_config.provider = "cpu";
|
||||
cfg.model_config.modeling_unit = "";
|
||||
cfg.decoding_method = "greedy_search";
|
||||
cfg.max_active_paths = 4;
|
||||
cfg.enable_endpoint = 0; // 分段由我们的 VAD 负责
|
||||
|
||||
d->rec = SherpaOnnxCreateOnlineRecognizer(&cfg);
|
||||
if (!d->rec) return fail("创建 sherpa-onnx 识别器失败(检查模型文件)");
|
||||
|
||||
d->stream = SherpaOnnxCreateOnlineStream(d->rec);
|
||||
if (!d->stream) return fail("创建 sherpa-onnx 流失败");
|
||||
if (!opt.language.empty()) {
|
||||
SherpaOnnxOnlineStreamSetOption(d->stream, "language", opt.language.c_str());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string SherpaAsr::streamFeed(const float * pcm, size_t n)
|
||||
{
|
||||
if (!d->rec || !d->stream) return {};
|
||||
SherpaOnnxOnlineStreamAcceptWaveform(d->stream, 16000, pcm, (int32_t) n);
|
||||
d->drain();
|
||||
return d->resultText();
|
||||
}
|
||||
|
||||
std::string SherpaAsr::streamFinish()
|
||||
{
|
||||
if (!d->rec || !d->stream) return {};
|
||||
// 先补一小段静音再结束,否则最后一个字常常来不及输出
|
||||
const size_t pad = (size_t) (16000 * 0.3);
|
||||
const std::vector<float> silence(pad, 0.0f);
|
||||
SherpaOnnxOnlineStreamAcceptWaveform(d->stream, 16000, silence.data(), (int32_t) pad);
|
||||
d->drain();
|
||||
// 注意:这里**不调用 InputFinished**。
|
||||
// 实时字幕的音频流是永不结束的,一句话的边界是"静音"而不是"输入结束";
|
||||
// InputFinished 的语义(再也不会有音频了)对文件才成立,对我们不适用。
|
||||
// 只需要补一小段静音,让模型把最后一个字吐出来即可。
|
||||
return d->resultText();
|
||||
}
|
||||
|
||||
void SherpaAsr::streamReset()
|
||||
{
|
||||
if (!d->rec || !d->stream) return;
|
||||
SherpaOnnxOnlineStreamReset(d->rec, d->stream);
|
||||
}
|
||||
|
||||
AsrResult SherpaAsr::transcribeWithPrefix(const float *, size_t, const std::string &)
|
||||
{
|
||||
AsrResult r;
|
||||
r.ok = false;
|
||||
r.error = "该后端只支持原生流式(NativeStreaming),不支持整段/前缀回滚模式";
|
||||
return r;
|
||||
}
|
||||
|
||||
AsrStreamStep SherpaAsr::streamAppend(const float *, size_t, const std::string &, int)
|
||||
{
|
||||
AsrStreamStep s;
|
||||
s.ok = false;
|
||||
s.error = "该后端只支持原生流式(NativeStreaming),请用 streamFeed()";
|
||||
return s;
|
||||
}
|
||||
|
||||
AsrStreamStep SherpaAsr::streamAppendTurn(const float *, size_t, int)
|
||||
{
|
||||
AsrStreamStep s;
|
||||
s.ok = false;
|
||||
s.error = "该后端只支持原生流式(NativeStreaming),请用 streamFeed()";
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "iasr.h"
|
||||
|
||||
struct SherpaOnnxOnlineRecognizer;
|
||||
struct SherpaOnnxOnlineStream;
|
||||
|
||||
namespace lc {
|
||||
|
||||
// sherpa-onnx 的流式识别器(X-ASR / zipformer / Nemotron …)。
|
||||
//
|
||||
// 用的是它的 **C API** 而不是 C++ API:预编译库是用旧 C++ ABI
|
||||
// (_GLIBCXX_USE_CXX11_ABI=0)编的,和 Qt 的新 ABI 不兼容;C API 是 extern "C",
|
||||
// 不经过 C++ 名字改写,没有这个问题。
|
||||
//
|
||||
// 这类模型是**有状态流式**:喂音频 → 随时取当前整句文本(会修正前面的词)。
|
||||
class SherpaAsr : public IAsr {
|
||||
public:
|
||||
struct Options {
|
||||
std::string encoder;
|
||||
std::string decoder;
|
||||
std::string joiner;
|
||||
std::string tokens;
|
||||
int threads = 1; // 注意:这类模型单线程反而最快
|
||||
std::string language; // 多语言模型(如 Nemotron)用;空 = 不设置
|
||||
};
|
||||
|
||||
SherpaAsr();
|
||||
~SherpaAsr() override;
|
||||
|
||||
SherpaAsr(const SherpaAsr &) = delete;
|
||||
SherpaAsr & operator=(const SherpaAsr &) = delete;
|
||||
|
||||
bool load(const Options & opt, std::string * error);
|
||||
|
||||
AsrKind kind() const override { return AsrKind::NativeStreaming; }
|
||||
int sampleRate() const override { return 16000; }
|
||||
|
||||
std::string streamFeed(const float * pcm, size_t n) override;
|
||||
std::string streamFinish() override;
|
||||
void streamReset() override;
|
||||
|
||||
// 这些只对 PrefixRollback 后端有意义;这里给出明确的失败信息
|
||||
AsrResult transcribeWithPrefix(const float *, size_t, const std::string &) override;
|
||||
AsrStreamStep streamAppend(const float *, size_t, const std::string &, int) override;
|
||||
AsrStreamStep streamAppendTurn(const float *, size_t, int) override;
|
||||
std::string dropLastTokens(const std::string & text, int) const override { return text; }
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
Impl * d = nullptr;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,285 @@
|
||||
#include "streamingasr.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
|
||||
#include "transcript.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace {
|
||||
|
||||
// 去掉首尾空白(含末尾空格),用于 sherpa 这类可能带前导空格的输出
|
||||
std::string trimAscii(const std::string & s)
|
||||
{
|
||||
const auto notSpace = [](unsigned char c) { return !std::isspace(c); };
|
||||
auto b = std::find_if(s.begin(), s.end(), notSpace);
|
||||
auto e = std::find_if(s.rbegin(), s.rend(), notSpace).base();
|
||||
if (b >= e) return {};
|
||||
return std::string(b, e);
|
||||
}
|
||||
|
||||
// 两个字符串的最长公共前缀,切在 UTF-8 字符边界上
|
||||
size_t utf8Lcp(const std::string & a, const std::string & b)
|
||||
{
|
||||
const size_t n = std::min(a.size(), b.size());
|
||||
size_t i = 0;
|
||||
while (i < n && a[i] == b[i]) ++i;
|
||||
while (i > 0 && (static_cast<unsigned char>(a[i]) & 0xC0) == 0x80) --i;
|
||||
return i;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StreamingAsr::StreamingAsr(IAsr & asr, StreamOptions opt)
|
||||
: asr_(asr), opt_(opt)
|
||||
{
|
||||
asr_.streamReset();
|
||||
}
|
||||
|
||||
void StreamingAsr::reset()
|
||||
{
|
||||
asr_.streamReset();
|
||||
buffer_.clear();
|
||||
pending_.clear();
|
||||
totalSeconds_ = 0.0;
|
||||
committedRaw_.clear();
|
||||
lastRawFull_.clear();
|
||||
previousFull_.clear();
|
||||
language_.clear();
|
||||
chunkIndex_ = 0;
|
||||
}
|
||||
|
||||
void StreamingAsr::resetAll()
|
||||
{
|
||||
reset();
|
||||
historyText_.clear();
|
||||
}
|
||||
|
||||
std::string StreamingAsr::committedText() const
|
||||
{
|
||||
return historyText_ + parseAsrOutput(committedRaw_).text;
|
||||
}
|
||||
|
||||
void StreamingAsr::feed(const float * pcm, size_t n,
|
||||
const std::function<void(const Step &)> & onStep)
|
||||
{
|
||||
pending_.insert(pending_.end(), pcm, pcm + n);
|
||||
|
||||
const size_t chunkSamples = (size_t) (opt_.chunkSec * asr_.sampleRate());
|
||||
if (chunkSamples == 0) return;
|
||||
|
||||
while (pending_.size() >= chunkSamples) {
|
||||
std::vector<float> chunk(pending_.begin(), pending_.begin() + (long) chunkSamples);
|
||||
pending_.erase(pending_.begin(), pending_.begin() + (long) chunkSamples);
|
||||
runStep(chunk, false, onStep);
|
||||
}
|
||||
}
|
||||
|
||||
void StreamingAsr::flush(const std::function<void(const Step &)> & onStep)
|
||||
{
|
||||
// 原生流式:把尾部 flush 出来即收尾(streamFinish 会补齐最后一个字)
|
||||
if (asr_.kind() == AsrKind::NativeStreaming) {
|
||||
std::vector<float> chunk;
|
||||
chunk.swap(pending_);
|
||||
runStep(chunk, true, onStep);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!pending_.empty()) {
|
||||
std::vector<float> chunk;
|
||||
chunk.swap(pending_);
|
||||
// 流结束:没有更多音频可以修正尾部了,这一步全部提交
|
||||
runStep(chunk, true, onStep);
|
||||
return;
|
||||
}
|
||||
|
||||
// 没有待处理音频:直接把这一段提交掉。
|
||||
// 注意要用 lastRawFull_(含不稳定尾部)而不是 committedRaw_:
|
||||
// 段恰好结束在 chunk 边界时,否则最后几个词会被丢掉。
|
||||
const std::string full = lastRawFull_.empty() ? committedRaw_ : lastRawFull_;
|
||||
if (full.empty()) return;
|
||||
|
||||
historyText_ += parseAsrOutput(full).text;
|
||||
committedRaw_.clear();
|
||||
lastRawFull_.clear();
|
||||
|
||||
Step s;
|
||||
s.chunkIndex = chunkIndex_;
|
||||
s.language = language_;
|
||||
s.ok = true;
|
||||
s.full = historyText_;
|
||||
s.committed = historyText_;
|
||||
if (onStep) onStep(s);
|
||||
|
||||
// 收束这一段
|
||||
asr_.streamReset();
|
||||
buffer_.clear();
|
||||
totalSeconds_ = 0.0;
|
||||
chunkIndex_ = 0;
|
||||
}
|
||||
|
||||
void StreamingAsr::runStep(const std::vector<float> & audio, bool finalStep,
|
||||
const std::function<void(const Step &)> & onStep)
|
||||
{
|
||||
// ---- 原生流式(sherpa-onnx 这类有状态识别器)----
|
||||
// 它自己维护状态并随时给出整句文本,会修正前面的词;我们只负责:
|
||||
// 1) 把音频喂进去
|
||||
// 2) 用"与上一次的公共前缀"作为已稳定部分,其余算不稳定尾部
|
||||
if (asr_.kind() == AsrKind::NativeStreaming) {
|
||||
Step s;
|
||||
s.chunkIndex = chunkIndex_;
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::string cur;
|
||||
if (!audio.empty()) cur = asr_.streamFeed(audio.data(), audio.size());
|
||||
if (finalStep) cur = asr_.streamFinish();
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
|
||||
s.ok = true;
|
||||
s.inferSeconds = std::chrono::duration<double>(t1 - t0).count();
|
||||
s.full = trimAscii(cur);
|
||||
|
||||
const std::string stable = s.full.substr(0, utf8Lcp(previousFull_, s.full));
|
||||
previousFull_ = s.full;
|
||||
s.committed = stable;
|
||||
s.tail = s.full.substr(stable.size());
|
||||
s.language = language_;
|
||||
|
||||
totalSeconds_ += (double) audio.size() / asr_.sampleRate();
|
||||
s.windowSeconds = totalSeconds_;
|
||||
|
||||
++chunkIndex_;
|
||||
if (onStep) onStep(s);
|
||||
|
||||
if (finalStep) {
|
||||
// 这一句结束:并入历史,等下一次 reset()
|
||||
historyText_ += s.full;
|
||||
previousFull_.clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 冷启动阶段不给前缀;之后把"已稳定文本"回喂给模型
|
||||
const std::string prefix =
|
||||
(chunkIndex_ >= opt_.unfixedChunkNum) ? committedRaw_ : std::string();
|
||||
|
||||
Step s;
|
||||
s.chunkIndex = chunkIndex_;
|
||||
|
||||
std::string newText;
|
||||
if (opt_.appendOnly) {
|
||||
// 追加式:这一块作为一个新的对话轮,文本随即定稿,不做前缀回滚
|
||||
AsrStreamStep r = asr_.streamAppendTurn(audio.data(), audio.size(),
|
||||
opt_.maxTokensPerStep);
|
||||
s.ok = r.ok;
|
||||
s.error = r.error;
|
||||
s.encodeSeconds = r.encodeSeconds;
|
||||
s.prefillSeconds = r.prefillSeconds;
|
||||
s.genSeconds = r.genSeconds;
|
||||
s.inferSeconds = r.inferSeconds;
|
||||
s.audioTokens = r.audioTokens;
|
||||
s.newTokens = r.newTokens;
|
||||
newText = r.newText;
|
||||
totalSeconds_ += (double) audio.size() / asr_.sampleRate();
|
||||
s.windowSeconds = totalSeconds_;
|
||||
} else if (opt_.incremental) {
|
||||
// 只把这一块交给增量引擎;音频总长不影响单步成本
|
||||
AsrStreamStep r =
|
||||
asr_.streamAppend(audio.data(), audio.size(), prefix, opt_.maxTokensPerStep);
|
||||
s.ok = r.ok;
|
||||
s.error = r.error;
|
||||
s.encodeSeconds = r.encodeSeconds;
|
||||
s.prefillSeconds = r.prefillSeconds;
|
||||
s.genSeconds = r.genSeconds;
|
||||
s.inferSeconds = r.inferSeconds;
|
||||
s.audioTokens = r.audioTokens;
|
||||
s.newTokens = r.newTokens;
|
||||
newText = r.newText;
|
||||
totalSeconds_ += (double) audio.size() / asr_.sampleRate();
|
||||
s.windowSeconds = totalSeconds_;
|
||||
} else {
|
||||
// window 模式:累积到 buffer,滑动窗口后重编码整个窗口
|
||||
buffer_.insert(buffer_.end(), audio.begin(), audio.end());
|
||||
if (opt_.windowSec > 0) {
|
||||
const size_t maxSamples = (size_t) (opt_.windowSec * asr_.sampleRate());
|
||||
if (buffer_.size() > maxSamples) {
|
||||
buffer_.erase(buffer_.begin(),
|
||||
buffer_.begin() + (long) (buffer_.size() - maxSamples));
|
||||
}
|
||||
}
|
||||
AsrResult r =
|
||||
asr_.transcribeWithPrefix(buffer_.data(), buffer_.size(), prefix);
|
||||
s.ok = r.ok;
|
||||
s.error = r.error;
|
||||
s.inferSeconds = r.inferSeconds;
|
||||
s.windowSeconds = (double) buffer_.size() / asr_.sampleRate();
|
||||
newText = r.raw;
|
||||
}
|
||||
|
||||
if (s.ok) {
|
||||
if (opt_.appendOnly) {
|
||||
// 追加式:每轮文本直接定稿,追加进历史,没有"不稳定尾部"
|
||||
const ParsedTranscript pTurn = parseAsrOutput(newText);
|
||||
if (!pTurn.language.empty()) language_ = pTurn.language;
|
||||
historyText_ += pTurn.text;
|
||||
s.rawFull = newText;
|
||||
s.full = historyText_;
|
||||
s.committed = historyText_;
|
||||
s.tail.clear();
|
||||
s.language = language_;
|
||||
lastRawFull_.clear();
|
||||
committedRaw_.clear();
|
||||
++chunkIndex_;
|
||||
if (onStep) onStep(s);
|
||||
return;
|
||||
}
|
||||
|
||||
// 拼接要用未经 trim 的文本:流式续写时开头那个空格是有意义的
|
||||
s.rawFull = prefix + newText;
|
||||
lastRawFull_ = s.rawFull;
|
||||
|
||||
const ParsedTranscript pSeg = parseAsrOutput(s.rawFull);
|
||||
if (!pSeg.language.empty()) language_ = pSeg.language;
|
||||
|
||||
// 这一段是否到此为止(流结束,或超过单段时长上限)
|
||||
const bool endSegment =
|
||||
finalStep || (opt_.maxUtteranceSec > 0 && totalSeconds_ >= opt_.maxUtteranceSec);
|
||||
|
||||
if (endSegment) {
|
||||
// 没有更多音频可以修正尾部了,全部提交,并把正文并入历史
|
||||
committedRaw_ = s.rawFull;
|
||||
historyText_ += pSeg.text;
|
||||
s.full = historyText_;
|
||||
s.committed = historyText_;
|
||||
s.tail.clear();
|
||||
} else {
|
||||
// 最后 unfixedTokenNum 个 token 视为不稳定,不提交也不回喂
|
||||
committedRaw_ = asr_.dropLastTokens(s.rawFull, opt_.unfixedTokenNum);
|
||||
const std::string committedSeg = parseAsrOutput(committedRaw_).text;
|
||||
s.full = historyText_ + pSeg.text;
|
||||
s.committed = historyText_ + committedSeg;
|
||||
// 不稳定尾部 = 本段文本去掉已稳定的那部分
|
||||
s.tail = s.full.size() > s.committed.size()
|
||||
? s.full.substr(s.committed.size())
|
||||
: std::string();
|
||||
}
|
||||
s.language = language_;
|
||||
}
|
||||
|
||||
++chunkIndex_;
|
||||
if (onStep) onStep(s);
|
||||
|
||||
if (s.ok && !finalStep &&
|
||||
opt_.maxUtteranceSec > 0 && totalSeconds_ >= opt_.maxUtteranceSec) {
|
||||
// 收束这一段:保留历史正文,清空 KV 重新开始
|
||||
asr_.streamReset();
|
||||
buffer_.clear();
|
||||
totalSeconds_ = 0.0;
|
||||
committedRaw_.clear();
|
||||
chunkIndex_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "iasr.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 官方流式解码的参数(见 docs/phase2-streaming.md)
|
||||
struct StreamOptions {
|
||||
double chunkSec = 2.0; // 累积多少秒音频跑一步
|
||||
double windowSec = 16.0; // 仅 window 模式使用:滑窗上限,<=0 表示不滑窗
|
||||
int unfixedTokenNum = 5; // 前缀回滚:丢掉最后 N 个 token
|
||||
int unfixedChunkNum = 2; // 前 N 个 chunk 不带前缀(冷启动)
|
||||
int maxTokensPerStep = 256;
|
||||
|
||||
// true = 增量 KV 复用:只编码新音频,已解码音频留在 KV(推荐)
|
||||
// false = 每次重编码整个窗口(Phase 2 早期的做法,仅用于对比)
|
||||
bool incremental = true;
|
||||
|
||||
// true = 追加式轮次(append-only):每块音频作为新一轮追加,前缀完全不重算、
|
||||
// 旧音频不重编码,单步成本与总长无关。代价是每块只用自己的长度编码
|
||||
// (没有 8s 上下文),准确率需实测确认。
|
||||
bool appendOnly = false;
|
||||
|
||||
// 单段最长时长(秒):超过就提交并重置上下文(0 = 不限)。
|
||||
// 真实场景应由静音检测决定分段;这里是一个兜底上界,
|
||||
// 因为解码器对 KV 的注意力随总长增长,段太长单步会超预算。
|
||||
double maxUtteranceSec = 30.0;
|
||||
};
|
||||
|
||||
// 把「累积音频 → 带前缀继续生成 → 前缀回滚」这套策略封装起来。
|
||||
// 输出分两部分:
|
||||
// committed —— 已稳定文本(就是下一步要回喂的前缀)
|
||||
// full —— 含不稳定尾部(最后 unfixedTokenNum 个 token)
|
||||
class StreamingAsr {
|
||||
public:
|
||||
struct Step {
|
||||
int chunkIndex = 0;
|
||||
std::string language;
|
||||
std::string committed; // 稳定部分
|
||||
std::string tail; // 不稳定尾部(committed 之后的部分)
|
||||
std::string full; // 含不稳定尾部
|
||||
std::string rawFull; // 未 trim 的完整文本(含 language 头)
|
||||
double windowSeconds = 0.0;
|
||||
double encodeSeconds = 0.0;
|
||||
double prefillSeconds = 0.0;
|
||||
double genSeconds = 0.0;
|
||||
double inferSeconds = 0.0;
|
||||
int audioTokens = 0;
|
||||
int newTokens = 0;
|
||||
bool ok = true;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
StreamingAsr(IAsr & asr, StreamOptions opt = {});
|
||||
|
||||
// 喂入 16k 单声道音频;每凑够 chunkSec 就跑一步并回调
|
||||
void feed(const float * pcm, size_t n, const std::function<void(const Step &)> & onStep);
|
||||
// 处理不足一块的残留音频,并作为最后一步提交全部文本。
|
||||
// 若没有待处理音频,也把当前已稳定文本提交为最终(静音分段时会用到)。
|
||||
void flush(const std::function<void(const Step &)> & onStep);
|
||||
|
||||
// 结束当前这段(例如检测到静音):清空 KV 与状态,下一段重新开始
|
||||
void reset();
|
||||
// 重置全部状态(含历史文本)
|
||||
void resetAll();
|
||||
|
||||
// 全部已提交文本(含此前各段,已剥离 language 头)
|
||||
std::string committedText() const;
|
||||
const std::string & language() const { return language_; }
|
||||
int chunkCount() const { return chunkIndex_; }
|
||||
|
||||
private:
|
||||
void runStep(const std::vector<float> & audio, bool finalStep,
|
||||
const std::function<void(const Step &)> & onStep);
|
||||
|
||||
IAsr & asr_;
|
||||
StreamOptions opt_;
|
||||
std::vector<float> buffer_; // window 模式:当前窗口音频
|
||||
std::vector<float> pending_; // 尚未凑够一块的音频
|
||||
double totalSeconds_ = 0.0;
|
||||
std::string committedRaw_; // 当前段的原始已提交文本(含 language 头,用于回喂)
|
||||
std::string lastRawFull_; // 上一次完整的原始文本(含不稳定尾部)
|
||||
std::string previousFull_; // 原生流式:上一次的完整文本(用来算已稳定的前缀)
|
||||
std::string historyText_; // 此前各段已提交的正文(已剥离 language 头)
|
||||
std::string language_;
|
||||
int chunkIndex_ = 0;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -76,4 +76,38 @@ std::string languageDisplayName(const std::string & lang)
|
||||
return lang;
|
||||
}
|
||||
|
||||
// ISO 639-1 码(注册表里用的形式,如 zh / en / ja)→ 显示名。
|
||||
// ASR 模型自己吐的是完整语言名(走上面的 languageDisplayName),
|
||||
// 但设置里的语言提示是 ISO 码,界面要显示成中文。
|
||||
std::string languageDisplayNameFromCode(const std::string & code)
|
||||
{
|
||||
if (code.empty()) return {};
|
||||
|
||||
static const struct { const char * key; const char * display; } kMap[] = {
|
||||
{ "zh", "中文" },
|
||||
{ "en", "英语" },
|
||||
{ "ja", "日语" },
|
||||
{ "ko", "韩语" },
|
||||
{ "fr", "法语" },
|
||||
{ "de", "德语" },
|
||||
{ "es", "西班牙语" },
|
||||
{ "ru", "俄语" },
|
||||
{ "it", "意大利语" },
|
||||
{ "pt", "葡萄牙语" },
|
||||
{ "ar", "阿拉伯语" },
|
||||
{ "hi", "印地语" },
|
||||
{ "vi", "越南语" },
|
||||
{ "nl", "荷兰语" },
|
||||
{ "tr", "土耳其语" },
|
||||
{ "uk", "乌克兰语" },
|
||||
{ "yue", "粤语" },
|
||||
{ "auto", "自动检测" },
|
||||
};
|
||||
|
||||
for (const auto & e : kMap) {
|
||||
if (code == e.key) return e.display;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -17,4 +17,7 @@ ParsedTranscript parseAsrOutput(const std::string & raw);
|
||||
// "English" -> "英语","Chinese" -> "中文";未知则原样返回
|
||||
std::string languageDisplayName(const std::string & lang);
|
||||
|
||||
// ISO 码(注册表里用的形式)-> 显示名:"zh" -> "中文"、"ja" -> "日语";未知则原样返回
|
||||
std::string languageDisplayNameFromCode(const std::string & code);
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 能量 VAD。
|
||||
//
|
||||
// 噪声底必须用"快降慢升"的**最小值跟踪**,不能用均值:
|
||||
// 否则遇到本身就很轻的音频(例如峰值 RMS 只有 0.03 的录音),
|
||||
// 噪声底会一路抬升、阈值超过语音电平,把绝大部分话音都判成静音。
|
||||
class Vad {
|
||||
public:
|
||||
explicit Vad(float floorInit = 0.01f, float factor = 3.0f, float minThreshold = 0.0015f)
|
||||
: floor_(floorInit), factor_(factor), minThreshold_(minThreshold) {}
|
||||
|
||||
// 返回该帧是否为语音
|
||||
bool feed(const float * frame, size_t n)
|
||||
{
|
||||
double acc = 0.0;
|
||||
for (size_t i = 0; i < n; ++i) acc += (double) frame[i] * frame[i];
|
||||
const float rms = std::sqrt(acc / (double) n);
|
||||
|
||||
if (rms < floor_) floor_ = rms; // 快速下探
|
||||
else floor_ = floor_ * 0.9999f + rms * 0.0001f; // 极慢回升
|
||||
|
||||
lastRms_ = rms;
|
||||
return rms > std::max(floor_ * factor_, minThreshold_);
|
||||
}
|
||||
|
||||
float noiseFloor() const { return floor_; }
|
||||
float lastRms() const { return lastRms_; }
|
||||
|
||||
private:
|
||||
float floor_;
|
||||
float factor_;
|
||||
float minThreshold_;
|
||||
float lastRms_ = 0.0f;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
-316
@@ -1,316 +0,0 @@
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <QCommandLineParser>
|
||||
#include <QCoreApplication>
|
||||
|
||||
#include "audio.h"
|
||||
#include "qwen3asr.h"
|
||||
#include "transcript.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kFrameSamples = 320; // 20ms @ 16k
|
||||
constexpr float kSilenceTimeout = 0.8f; // 静音多久算一句结束
|
||||
constexpr float kMinSpeech = 0.5f; // 一句话至少多长才值得转写
|
||||
constexpr float kMaxWindow = 20.0f; // 窗口上限,超过强制收尾
|
||||
|
||||
// 两个字符串的最长公共前缀,且保证切在 UTF-8 字符边界上
|
||||
size_t utf8Lcp(const std::string & a, const std::string & b)
|
||||
{
|
||||
const size_t n = std::min(a.size(), b.size());
|
||||
size_t i = 0;
|
||||
while (i < n && a[i] == b[i]) ++i;
|
||||
// 回退到不是 UTF-8 续字节(10xxxxxx)的位置
|
||||
while (i > 0 && (static_cast<unsigned char>(a[i]) & 0xC0) == 0x80) --i;
|
||||
return i;
|
||||
}
|
||||
|
||||
// 简单的能量 VAD。
|
||||
// 噪声底必须用"最小值跟踪"(快降慢升),不能用均值:
|
||||
// 否则遇到本来就很轻的音频(例如 AISHELL 峰值 RMS 只有 0.03),
|
||||
// 噪声底会一路抬升、阈值超过语音电平,把话音全判成静音。
|
||||
class Vad {
|
||||
public:
|
||||
// 返回该帧是否为语音
|
||||
bool feed(const float * frame, size_t n)
|
||||
{
|
||||
double acc = 0.0;
|
||||
for (size_t i = 0; i < n; ++i) acc += (double) frame[i] * frame[i];
|
||||
const float rms = std::sqrt(acc / (double) n);
|
||||
|
||||
if (rms < floor_) {
|
||||
floor_ = rms; // 快速下探
|
||||
} else {
|
||||
floor_ = floor_ * 0.9999f + rms * 0.0001f; // 极慢回升
|
||||
}
|
||||
|
||||
const float threshold = std::max(floor_ * 3.0f, 0.0015f);
|
||||
speech_ = rms > threshold;
|
||||
return speech_;
|
||||
}
|
||||
|
||||
bool speaking() const { return speech_; }
|
||||
|
||||
private:
|
||||
float floor_ = 0.01f;
|
||||
bool speech_ = false;
|
||||
};
|
||||
|
||||
// 实时转写:采集线程 -> 队列 -> 工作线程(VAD + 滑窗 + 转写)
|
||||
class LiveTranscriber {
|
||||
public:
|
||||
LiveTranscriber(lc::Qwen3Asr & asr, int sampleRate) : asr_(asr), sampleRate_(sampleRate) {}
|
||||
|
||||
void onAudio(const float * samples, size_t n)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
pending_.insert(pending_.end(), samples, samples + n);
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
void start() { worker_ = std::thread([this] { run(); }); }
|
||||
|
||||
void stop()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
quit_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
if (worker_.joinable()) worker_.join();
|
||||
}
|
||||
|
||||
private:
|
||||
void emitPartial(const lc::Qwen3Asr::Result & r)
|
||||
{
|
||||
// 只把"跨多次转写都不变"的前缀当成已定文本,尾部标为不稳定预览。
|
||||
// 窗口在词中间被切断时,模型会给尾部编一个结尾,这样能避免它上屏。
|
||||
committed_ = r.transcript.text.substr(0, utf8Lcp(committed_, r.transcript.text));
|
||||
const std::string tail = r.transcript.text.substr(committed_.size());
|
||||
|
||||
std::lock_guard<std::mutex> lk(printMutex_);
|
||||
std::printf("\r\033[K~ [%s] %s\033[2m%s\033[0m",
|
||||
lc::languageDisplayName(r.transcript.language).c_str(),
|
||||
committed_.c_str(), tail.c_str());
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
void emitFinal(const lc::Qwen3Asr::Result & r)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(printMutex_);
|
||||
std::printf("\r\033[K= [%s] %s\n",
|
||||
lc::languageDisplayName(r.transcript.language).c_str(),
|
||||
r.transcript.text.c_str());
|
||||
std::fflush(stdout);
|
||||
committed_.clear();
|
||||
}
|
||||
|
||||
lc::Qwen3Asr::Result transcribeWindow(const std::vector<float> & window)
|
||||
{
|
||||
lc::Qwen3Asr::Result r = asr_.transcribe(window.data(), window.size());
|
||||
const double dur = (double) window.size() / sampleRate_;
|
||||
std::lock_guard<std::mutex> lk(printMutex_);
|
||||
std::fprintf(stderr, " [infer] %.2fs 音频 / %.2fs 计算 (rtf %.3f)\n",
|
||||
dur, r.inferSeconds, dur > 0 ? r.inferSeconds / dur : 0.0);
|
||||
return r;
|
||||
}
|
||||
|
||||
void run()
|
||||
{
|
||||
Vad vad;
|
||||
std::vector<float> window; // 当前这句话累积的音频
|
||||
std::vector<float> buffer; // 跨批次残留,保证不丢样本
|
||||
float silenceAcc = 0.0f;
|
||||
float lastPartialAt = 0.0f; // 上次做 partial 时窗口长度(秒)
|
||||
|
||||
for (;;) {
|
||||
std::vector<float> chunk;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(mutex_);
|
||||
cv_.wait_for(lk, std::chrono::milliseconds(50), [this] { return quit_ || !pending_.empty(); });
|
||||
if (quit_ && pending_.empty()) break;
|
||||
chunk.swap(pending_);
|
||||
}
|
||||
|
||||
// 关键:把上一轮不足一帧的残留接上,否则会持续丢样本
|
||||
buffer.insert(buffer.end(), chunk.begin(), chunk.end());
|
||||
|
||||
size_t off = 0;
|
||||
for (; off + kFrameSamples <= buffer.size(); off += kFrameSamples) {
|
||||
const float * frame = buffer.data() + off;
|
||||
const bool speech = vad.feed(frame, kFrameSamples);
|
||||
|
||||
if (speech) {
|
||||
if (window.empty()) lastPartialAt = 0.0f;
|
||||
window.insert(window.end(), frame, frame + kFrameSamples);
|
||||
silenceAcc = 0.0f;
|
||||
} else if (!window.empty()) {
|
||||
window.insert(window.end(), frame, frame + kFrameSamples);
|
||||
silenceAcc += (float) kFrameSamples / sampleRate_;
|
||||
}
|
||||
|
||||
if (window.empty()) continue;
|
||||
|
||||
const float windowSec = (float) window.size() / sampleRate_;
|
||||
const float newAudioSincePartial = windowSec - lastPartialAt;
|
||||
const float needed = std::max(0.8f, 0.35f * windowSec);
|
||||
|
||||
// 静音够久 -> 收尾
|
||||
if (silenceAcc >= kSilenceTimeout && windowSec >= kMinSpeech) {
|
||||
emitFinal(transcribeWindow(window));
|
||||
window.clear();
|
||||
silenceAcc = 0.0f;
|
||||
lastPartialAt = 0.0f;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 窗口过长 -> 强制收尾,避免延迟无限增长
|
||||
if (windowSec >= kMaxWindow) {
|
||||
emitFinal(transcribeWindow(window));
|
||||
window.clear();
|
||||
silenceAcc = 0.0f;
|
||||
lastPartialAt = 0.0f;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 定期输出 partial(预览)
|
||||
if (newAudioSincePartial >= needed) {
|
||||
emitPartial(transcribeWindow(window));
|
||||
lastPartialAt = windowSec;
|
||||
}
|
||||
}
|
||||
|
||||
if (off > 0) buffer.erase(buffer.begin(), buffer.begin() + (long) off);
|
||||
}
|
||||
|
||||
if (!window.empty() && (float) window.size() / sampleRate_ >= kMinSpeech) {
|
||||
emitFinal(transcribeWindow(window));
|
||||
}
|
||||
}
|
||||
|
||||
lc::Qwen3Asr & asr_;
|
||||
int sampleRate_;
|
||||
std::thread worker_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<float> pending_;
|
||||
bool quit_ = false;
|
||||
std::mutex printMutex_;
|
||||
std::string committed_; // 当前这句已提交的稳定前缀
|
||||
};
|
||||
|
||||
int runFile(lc::Qwen3Asr & asr, const QString & path)
|
||||
{
|
||||
std::vector<float> pcm;
|
||||
std::string err;
|
||||
if (!lc::readWavMono(path.toStdString(), asr.sampleRate(), pcm, &err)) {
|
||||
std::fprintf(stderr, "读取音频失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
const double dur = (double) pcm.size() / asr.sampleRate();
|
||||
std::fprintf(stderr, "音频: %s (%.2fs)\n", qUtf8Printable(path), dur);
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
lc::Qwen3Asr::Result r = asr.transcribe(pcm.data(), pcm.size());
|
||||
const double wall = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
|
||||
if (!r.ok) {
|
||||
std::fprintf(stderr, "转写失败: %s\n", r.error.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::printf("语言: %s (%s)\n", r.transcript.language.c_str(),
|
||||
lc::languageDisplayName(r.transcript.language).c_str());
|
||||
std::printf("文本: %s\n", r.transcript.text.c_str());
|
||||
std::fprintf(stderr, "推理: %.2fs / 音频 %.2fs (rtf %.3f) 生成 %d tokens, 墙钟 %.2fs\n",
|
||||
r.inferSeconds, dur, dur > 0 ? r.inferSeconds / dur : 0, r.tokenCount, wall);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int runLive(lc::Qwen3Asr & asr)
|
||||
{
|
||||
LiveTranscriber live(asr, asr.sampleRate());
|
||||
lc::MonitorCapture capture;
|
||||
|
||||
std::string err;
|
||||
if (!capture.start(asr.sampleRate(), [&live](const float * s, size_t n) { live.onAudio(s, n); }, &err)) {
|
||||
std::fprintf(stderr, "启动采集失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::fprintf(stderr, "正在采集: %s (%d Hz)\n按 Ctrl+C 退出\n\n",
|
||||
capture.deviceName().c_str(), asr.sampleRate());
|
||||
|
||||
live.start();
|
||||
// 简单起见:主线程等待,Ctrl+C 结束进程
|
||||
for (;;) std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
QCoreApplication app(argc, argv);
|
||||
QCoreApplication::setApplicationName("live-caption");
|
||||
|
||||
QCommandLineParser parser;
|
||||
parser.setApplicationDescription("实时字幕原型(Qwen3-ASR + llama.cpp)");
|
||||
parser.addHelpOption();
|
||||
|
||||
QCommandLineOption optModel("model", "主模型 GGUF 路径(架构须为 qwen3vl)", "path");
|
||||
QCommandLineOption optMmproj("mmproj", "mmproj GGUF 路径(clip + qwen3a)", "path");
|
||||
QCommandLineOption optFile("file", "转写一个 wav 文件后退出(不开启实时采集)", "path");
|
||||
QCommandLineOption optThreads("threads", "推理线程数", "n", "8");
|
||||
QCommandLineOption optMaxTokens("max-tokens", "单段最多生成 token 数", "n", "256");
|
||||
QCommandLineOption optWarmup("warmup", "mtmd 初始化后做一次预热编码");
|
||||
QCommandLineOption optVerbose("verbose", "输出 llama.cpp/mtmd 的详细日志");
|
||||
|
||||
parser.addOption(optModel);
|
||||
parser.addOption(optMmproj);
|
||||
parser.addOption(optFile);
|
||||
parser.addOption(optThreads);
|
||||
parser.addOption(optMaxTokens);
|
||||
parser.addOption(optWarmup);
|
||||
parser.addOption(optVerbose);
|
||||
parser.process(app);
|
||||
|
||||
lc::AsrOptions asrOpt;
|
||||
asrOpt.modelPath = parser.value(optModel).toStdString();
|
||||
asrOpt.mmprojPath = parser.value(optMmproj).toStdString();
|
||||
asrOpt.threads = parser.value(optThreads).toInt();
|
||||
asrOpt.maxTokens = parser.value(optMaxTokens).toInt();
|
||||
asrOpt.warmup = parser.isSet(optWarmup);
|
||||
asrOpt.verbose = parser.isSet(optVerbose);
|
||||
|
||||
if (asrOpt.modelPath.empty() || asrOpt.mmprojPath.empty()) {
|
||||
std::fprintf(stderr, "必须提供 --model 和 --mmproj\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
lc::Qwen3Asr asr;
|
||||
std::string err;
|
||||
const auto tl0 = std::chrono::steady_clock::now();
|
||||
if (!asr.load(asrOpt, &err)) {
|
||||
std::fprintf(stderr, "加载失败: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(stderr, "模型加载完成: %.2fs (采样率 %d)\n",
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - tl0).count(),
|
||||
asr.sampleRate());
|
||||
|
||||
if (parser.isSet(optFile)) {
|
||||
return runFile(asr, parser.value(optFile));
|
||||
}
|
||||
return runLive(asr);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
#include "modeldownloader.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QUrl>
|
||||
|
||||
namespace lc::models {
|
||||
|
||||
ModelDownloader::ModelDownloader(QObject * parent) : QObject(parent) {}
|
||||
|
||||
ModelDownloader::~ModelDownloader() { cancel(); }
|
||||
|
||||
QString ModelDownloader::rewriteUrl(const QString & url) const
|
||||
{
|
||||
if (mirrorBase_.isEmpty()) return url;
|
||||
const QUrl u(url);
|
||||
QString base = mirrorBase_;
|
||||
while (base.endsWith(QLatin1Char('/'))) base.chop(1);
|
||||
return base + u.path();
|
||||
}
|
||||
|
||||
void ModelDownloader::start(const ModelInfo & model)
|
||||
{
|
||||
if (running_) return;
|
||||
running_ = true;
|
||||
cancel_ = false;
|
||||
index_ = 0;
|
||||
queue_ = model.files;
|
||||
dir_ = ModelStore::dirFor(model.id);
|
||||
|
||||
net_ = new QNetworkAccessManager(this);
|
||||
if (!proxy_.hostName().isEmpty() || proxy_.type() != QNetworkProxy::DefaultProxy) {
|
||||
net_->setProxy(proxy_);
|
||||
}
|
||||
|
||||
QDir().mkpath(dir_);
|
||||
startNextFile();
|
||||
}
|
||||
|
||||
void ModelDownloader::cancel()
|
||||
{
|
||||
cancel_ = true;
|
||||
running_ = false;
|
||||
if (reply_) {
|
||||
// 先彻底断开,再 abort:否则 abort 会同步触发 finished,
|
||||
// 而这时对话框可能正在析构、那些控件已经没了。
|
||||
disconnect(reply_, nullptr, this, nullptr);
|
||||
reply_->abort();
|
||||
reply_->deleteLater();
|
||||
reply_ = nullptr;
|
||||
}
|
||||
if (out_) {
|
||||
out_->close();
|
||||
delete out_;
|
||||
out_ = nullptr;
|
||||
}
|
||||
running_ = false;
|
||||
}
|
||||
|
||||
void ModelDownloader::startNextFile()
|
||||
{
|
||||
if (cancel_) { cleanup(); return; }
|
||||
if (index_ >= queue_.size()) {
|
||||
running_ = false;
|
||||
Q_EMIT status(QStringLiteral("下载完成"));
|
||||
Q_EMIT finished(true, QString());
|
||||
return;
|
||||
}
|
||||
|
||||
const ModelFile & f = queue_[index_];
|
||||
const QString path = dir_ + QLatin1Char('/') + f.name;
|
||||
out_ = new QFile(path);
|
||||
qint64 offset = 0;
|
||||
if (QFileInfo::exists(path)) offset = QFileInfo(path).size();
|
||||
|
||||
if (offset > 0) {
|
||||
if (!out_->open(QIODevice::ReadWrite)) {
|
||||
Q_EMIT finished(false, QStringLiteral("无法打开文件: ") + path);
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
out_->seek(offset);
|
||||
} else {
|
||||
offset = 0;
|
||||
if (!out_->open(QIODevice::WriteOnly)) {
|
||||
Q_EMIT finished(false, QStringLiteral("无法写入: ") + path);
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
QNetworkRequest req{QUrl(rewriteUrl(f.url))};
|
||||
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
|
||||
QNetworkRequest::NoLessSafeRedirectPolicy);
|
||||
if (offset > 0) {
|
||||
req.setRawHeader("Range", QByteArray("bytes=") + QByteArray::number(offset) + "-");
|
||||
Q_EMIT status(QStringLiteral("续传 %1").arg(f.name));
|
||||
} else {
|
||||
Q_EMIT status(QStringLiteral("下载 %1").arg(f.name));
|
||||
}
|
||||
|
||||
baseOffset_ = offset;
|
||||
reply_ = net_->get(req);
|
||||
connect(reply_, &QNetworkReply::readyRead, this, &ModelDownloader::onReadyRead);
|
||||
connect(reply_, &QNetworkReply::finished, this, &ModelDownloader::onFinished);
|
||||
connect(reply_, &QNetworkReply::downloadProgress, this,
|
||||
[this](qint64 got, qint64 tot) {
|
||||
Q_EMIT progress(queue_[index_].name,
|
||||
baseOffset_ + got,
|
||||
tot > 0 ? baseOffset_ + tot : -1);
|
||||
});
|
||||
}
|
||||
|
||||
void ModelDownloader::onReadyRead()
|
||||
{
|
||||
if (!reply_ || !out_) return;
|
||||
const QByteArray data = reply_->readAll();
|
||||
out_->write(data);
|
||||
}
|
||||
|
||||
void ModelDownloader::onFinished()
|
||||
{
|
||||
if (!reply_) return;
|
||||
const QNetworkReply::NetworkError err = reply_->error();
|
||||
const QString errText = reply_->errorString();
|
||||
if (out_) { out_->close(); delete out_; out_ = nullptr; }
|
||||
reply_->deleteLater();
|
||||
reply_ = nullptr;
|
||||
|
||||
if (err != QNetworkReply::NoError && err != QNetworkReply::OperationCanceledError) {
|
||||
running_ = false;
|
||||
Q_EMIT finished(false, QStringLiteral("下载失败: ") + errText);
|
||||
return;
|
||||
}
|
||||
if (cancel_) { cleanup(); return; }
|
||||
|
||||
++index_;
|
||||
startNextFile();
|
||||
}
|
||||
|
||||
void ModelDownloader::cleanup()
|
||||
{
|
||||
running_ = false;
|
||||
Q_EMIT finished(false, QStringLiteral("已取消"));
|
||||
}
|
||||
|
||||
|
||||
} // namespace lc::models
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <QNetworkProxy>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include "modelstore.h"
|
||||
|
||||
class QNetworkAccessManager;
|
||||
class QNetworkReply;
|
||||
class QFile;
|
||||
|
||||
namespace lc::models {
|
||||
|
||||
// 按注册表下载模型文件。支持:
|
||||
// - 镜像基址替换(把注册表里的地址换成用户选的源)
|
||||
// - HTTP 代理
|
||||
// - 断点续传(已下过的部分用 Range 续)
|
||||
class ModelDownloader : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ModelDownloader(QObject * parent = nullptr);
|
||||
~ModelDownloader() override;
|
||||
|
||||
// mirrorBase 形如 https://hf-mirror.com;留空则用注册表里的原始地址
|
||||
void setMirrorBase(const QString & mirrorBase) { mirrorBase_ = mirrorBase; }
|
||||
void setProxy(const QNetworkProxy & proxy) { proxy_ = proxy; }
|
||||
|
||||
void start(const ModelInfo & model);
|
||||
void cancel();
|
||||
bool isRunning() const { return running_; }
|
||||
|
||||
Q_SIGNALS:
|
||||
void progress(const QString & file, qint64 received, qint64 total);
|
||||
void status(const QString & message);
|
||||
void finished(bool ok, const QString & error);
|
||||
|
||||
private:
|
||||
void startNextFile();
|
||||
void onReadyRead();
|
||||
void onFinished();
|
||||
void cleanup();
|
||||
|
||||
QString rewriteUrl(const QString & url) const;
|
||||
|
||||
QNetworkAccessManager * net_ = nullptr;
|
||||
QNetworkReply * reply_ = nullptr;
|
||||
QFile * out_ = nullptr;
|
||||
std::vector<ModelFile> queue_;
|
||||
size_t index_ = 0;
|
||||
QString dir_;
|
||||
QString mirrorBase_;
|
||||
QNetworkProxy proxy_;
|
||||
bool running_ = false;
|
||||
bool cancel_ = false;
|
||||
qint64 baseOffset_ = 0; // 断点续传的起始偏移
|
||||
};
|
||||
|
||||
} // namespace lc::models
|
||||
@@ -0,0 +1,152 @@
|
||||
#include "modelstore.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QStandardPaths>
|
||||
|
||||
namespace lc::models {
|
||||
|
||||
namespace {
|
||||
|
||||
QString g_rootOverride;
|
||||
|
||||
const std::vector<ModelInfo> & parseRegistry()
|
||||
{
|
||||
static std::vector<ModelInfo> cache;
|
||||
static bool loaded = false;
|
||||
if (loaded) return cache;
|
||||
loaded = true;
|
||||
|
||||
QFile f(QStringLiteral(":/data/models.json"));
|
||||
if (!f.open(QIODevice::ReadOnly)) {
|
||||
qWarning("无法读取内嵌的模型注册表");
|
||||
return cache;
|
||||
}
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(f.readAll());
|
||||
for (const QJsonValue & v : doc.object().value(QStringLiteral("models")).toArray()) {
|
||||
const QJsonObject o = v.toObject();
|
||||
ModelInfo m;
|
||||
m.id = o.value(QStringLiteral("id")).toString();
|
||||
m.name = o.value(QStringLiteral("name")).toString();
|
||||
m.license = o.value(QStringLiteral("license")).toString();
|
||||
m.note = o.value(QStringLiteral("note")).toString();
|
||||
m.backend = (o.value(QStringLiteral("backend")).toString() == QLatin1String("llama-cpp"))
|
||||
? Backend::LlamaCpp
|
||||
: Backend::SherpaOnline;
|
||||
for (const QJsonValue & l : o.value(QStringLiteral("languages")).toArray()) {
|
||||
m.languages << l.toString();
|
||||
}
|
||||
const QJsonObject files = o.value(QStringLiteral("files")).toObject();
|
||||
for (auto it = files.begin(); it != files.end(); ++it) {
|
||||
const QJsonObject fo = it.value().toObject();
|
||||
ModelFile mf;
|
||||
mf.key = it.key();
|
||||
mf.name = fo.value(QStringLiteral("name")).toString();
|
||||
mf.url = fo.value(QStringLiteral("url")).toString();
|
||||
mf.size = (qint64) fo.value(QStringLiteral("size")).toDouble();
|
||||
mf.sha256 = fo.value(QStringLiteral("sha256")).toString();
|
||||
m.files.push_back(std::move(mf));
|
||||
}
|
||||
cache.push_back(std::move(m));
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void ModelStore::setRootOverride(const QString & dir) { g_rootOverride = dir; }
|
||||
|
||||
QString ModelStore::root()
|
||||
{
|
||||
if (!g_rootOverride.isEmpty()) return g_rootOverride;
|
||||
// 用 GenericDataLocation(~/.local/share)+ 固定名,保证 CLI/GUI 一致,
|
||||
// 也和 scripts/fetch-models.sh 的目录规则对得上。
|
||||
const QString base = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
|
||||
return base + QStringLiteral("/live-caption/models");
|
||||
}
|
||||
|
||||
QString ModelStore::dirFor(const QString & id) { return root() + QLatin1Char('/') + id; }
|
||||
|
||||
QString ModelInfo::filePath(const QString & key) const
|
||||
{
|
||||
for (const ModelFile & f : files) {
|
||||
if (f.key == key) return ModelStore::dirFor(id) + QLatin1Char('/') + f.name;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::vector<ModelInfo> & ModelStore::registry() { return parseRegistry(); }
|
||||
|
||||
const ModelInfo * ModelStore::find(const QString & id)
|
||||
{
|
||||
for (const ModelInfo & m : registry()) {
|
||||
if (m.id == id) return &m;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool ModelStore::isInstalled(const ModelInfo & m, QStringList * missing)
|
||||
{
|
||||
bool ok = true;
|
||||
for (const ModelFile & f : m.files) {
|
||||
const QString p = ModelStore::dirFor(m.id) + QLatin1Char('/') + f.name;
|
||||
const QFileInfo fi(p);
|
||||
const bool badSize = (f.size > 0) && (fi.size() != f.size);
|
||||
if (!fi.exists() || fi.size() == 0 || badSize) {
|
||||
ok = false;
|
||||
if (missing) *missing << f.name;
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool ModelStore::verify(const ModelInfo & m, QStringList * bad,
|
||||
const std::function<void(int, int)> & progress)
|
||||
{
|
||||
bool ok = true;
|
||||
int i = 0;
|
||||
for (const ModelFile & f : m.files) {
|
||||
if (progress) progress(i, (int) m.files.size());
|
||||
++i;
|
||||
const QString p = ModelStore::dirFor(m.id) + QLatin1Char('/') + f.name;
|
||||
QFile file(p);
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
ok = false;
|
||||
if (bad) *bad << f.name;
|
||||
continue;
|
||||
}
|
||||
if (!f.sha256.isEmpty()) {
|
||||
QCryptographicHash h(QCryptographicHash::Sha256);
|
||||
if (!h.addData(&file)) {
|
||||
ok = false;
|
||||
if (bad) *bad << f.name;
|
||||
continue;
|
||||
}
|
||||
if (QString::fromLatin1(h.result().toHex()) != f.sha256) {
|
||||
ok = false;
|
||||
if (bad) *bad << f.name;
|
||||
}
|
||||
} else if (f.size > 0 && file.size() != f.size) {
|
||||
ok = false;
|
||||
if (bad) *bad << f.name;
|
||||
}
|
||||
}
|
||||
if (progress) progress(i, (int) m.files.size());
|
||||
return ok;
|
||||
}
|
||||
|
||||
const ModelInfo * ModelStore::pickForLanguage(const QString & lang)
|
||||
{
|
||||
// 先找语言列表里明确包含该语言、且已安装的
|
||||
for (const ModelInfo & m : registry()) {
|
||||
if (m.languages.contains(lang) && isInstalled(m)) return &m;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace lc::models
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
// 模型注册表与存储。
|
||||
//
|
||||
// 存储位置遵循 XDG:<AppDataLocation>/models/<id>/,即
|
||||
// ~/.local/share/live-caption/models/<id>/
|
||||
// 注册表是 data/models.json(编译进二进制),新增模型只加一条数据,不改代码。
|
||||
namespace lc::models {
|
||||
|
||||
enum class Backend {
|
||||
SherpaOnline, // sherpa-onnx 的流式识别器(X-ASR / zipformer / Nemotron …)
|
||||
LlamaCpp, // ggml / llama.cpp(GGUF,例如 Qwen3-ASR)
|
||||
};
|
||||
|
||||
struct ModelFile {
|
||||
QString key; // encoder / decoder / joiner / tokens / model / mmproj
|
||||
QString name; // 文件名
|
||||
QString url; // 下载地址
|
||||
qint64 size = 0; // 字节数(0 = 注册表没写)
|
||||
QString sha256; // 期望的 sha256(空 = 不校验)
|
||||
};
|
||||
|
||||
struct ModelInfo {
|
||||
QString id;
|
||||
QString name;
|
||||
QString license;
|
||||
QString note;
|
||||
Backend backend = Backend::SherpaOnline;
|
||||
QStringList languages;
|
||||
std::vector<ModelFile> files;
|
||||
|
||||
QString filePath(const QString & key) const; // <store>/<id>/<name>
|
||||
};
|
||||
|
||||
class ModelStore {
|
||||
public:
|
||||
static QString root(); // 模型根目录
|
||||
static QString dirFor(const QString & id);
|
||||
|
||||
static const std::vector<ModelInfo> & registry();
|
||||
static const ModelInfo * find(const QString & id);
|
||||
|
||||
// 快速检查:文件齐全且大小对得上(注册表里写了 size 时)
|
||||
static bool isInstalled(const ModelInfo & m, QStringList * missing = nullptr);
|
||||
|
||||
// 完整校验:逐个重算 sha256。bad 返回有问题的文件;progress(done,total) 可选
|
||||
static bool verify(const ModelInfo & m, QStringList * bad = nullptr,
|
||||
const std::function<void(int, int)> & progress = {});
|
||||
|
||||
// 按语言挑一个已安装的模型(优先语言列表里排前的)
|
||||
static const ModelInfo * pickForLanguage(const QString & lang);
|
||||
|
||||
// 手工指定模型目录时,用这个覆盖 root()
|
||||
static void setRootOverride(const QString & dir);
|
||||
};
|
||||
|
||||
} // namespace lc::models
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "qwen3asr.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
#include <llama.h>
|
||||
#include <mtmd.h>
|
||||
#include <mtmd-helper.h>
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string defaultQwenChatPrompt(const std::string & content)
|
||||
{
|
||||
// Qwen3-ASR 的 chat template 就是标准 ChatML(见模型 GGUF 的 tokenizer.chat_template)
|
||||
return "<|im_start|>user\n" + content + "<|im_end|>\n<|im_start|>assistant\n";
|
||||
}
|
||||
|
||||
void silentLog(ggml_log_level /*level*/, const char * /*text*/, void * /*user*/) {}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct Qwen3Asr::Impl {
|
||||
AsrOptions opt;
|
||||
llama_model * model = nullptr;
|
||||
llama_context * ctx = nullptr;
|
||||
mtmd_context * mctx = nullptr;
|
||||
const llama_vocab * vocab = nullptr;
|
||||
int audioRate = 16000;
|
||||
|
||||
std::string buildPrompt(const std::string & marker) const
|
||||
{
|
||||
const char * tmpl = llama_model_chat_template(model, nullptr);
|
||||
if (tmpl) {
|
||||
llama_chat_message msg{"user", marker.c_str()};
|
||||
std::vector<char> buf(marker.size() * 2 + 4096);
|
||||
const int32_t n = llama_chat_apply_template(tmpl, &msg, 1, true, buf.data(), (int32_t) buf.size());
|
||||
if (n > 0 && (size_t) n <= buf.size()) {
|
||||
return std::string(buf.data(), (size_t) n);
|
||||
}
|
||||
}
|
||||
return defaultQwenChatPrompt(marker);
|
||||
}
|
||||
};
|
||||
|
||||
Qwen3Asr::Qwen3Asr() : d(new Impl) {}
|
||||
|
||||
Qwen3Asr::~Qwen3Asr()
|
||||
{
|
||||
if (!d) return;
|
||||
if (d->mctx) mtmd_free(d->mctx);
|
||||
if (d->ctx) llama_free(d->ctx);
|
||||
if (d->model) llama_model_free(d->model);
|
||||
delete d;
|
||||
}
|
||||
|
||||
int Qwen3Asr::sampleRate() const { return d->audioRate; }
|
||||
|
||||
bool Qwen3Asr::load(const AsrOptions & opt, std::string * error)
|
||||
{
|
||||
const auto fail = [error](const std::string & msg) {
|
||||
if (error) *error = msg;
|
||||
return false;
|
||||
};
|
||||
|
||||
d->opt = opt;
|
||||
|
||||
if (!opt.verbose) {
|
||||
llama_log_set(silentLog, nullptr);
|
||||
mtmd_log_set(silentLog, nullptr);
|
||||
}
|
||||
|
||||
llama_backend_init();
|
||||
|
||||
llama_model_params mparams = llama_model_default_params();
|
||||
mparams.n_gpu_layers = 0; // 本机无独显,强制 CPU
|
||||
mparams.use_mmap = true;
|
||||
|
||||
d->model = llama_model_load_from_file(opt.modelPath.c_str(), mparams);
|
||||
if (!d->model) {
|
||||
return fail("加载主模型失败: " + opt.modelPath);
|
||||
}
|
||||
d->vocab = llama_model_get_vocab(d->model);
|
||||
|
||||
llama_context_params cparams = llama_context_default_params();
|
||||
cparams.n_ctx = (uint32_t) opt.nCtx;
|
||||
cparams.n_batch = (uint32_t) opt.nBatch;
|
||||
cparams.n_ubatch = (uint32_t) opt.nUbatch;
|
||||
cparams.n_threads = opt.threads;
|
||||
cparams.n_threads_batch = opt.threads;
|
||||
|
||||
d->ctx = llama_init_from_model(d->model, cparams);
|
||||
if (!d->ctx) {
|
||||
return fail("创建 llama 上下文失败");
|
||||
}
|
||||
|
||||
mtmd_context_params mctxParams = mtmd_context_params_default();
|
||||
mctxParams.use_gpu = false;
|
||||
mctxParams.n_threads = opt.threads;
|
||||
mctxParams.print_timings = false;
|
||||
mctxParams.warmup = opt.warmup;
|
||||
|
||||
d->mctx = mtmd_init_from_file(opt.mmprojPath.c_str(), d->model, mctxParams);
|
||||
if (!d->mctx) {
|
||||
return fail("加载 mmproj 失败: " + opt.mmprojPath);
|
||||
}
|
||||
|
||||
if (!mtmd_support_audio(d->mctx)) {
|
||||
return fail("该 mmproj 不支持音频输入(需要 clip.projector_type = qwen3a 的版本)");
|
||||
}
|
||||
|
||||
const int rate = mtmd_get_audio_sample_rate(d->mctx);
|
||||
if (rate > 0) d->audioRate = rate;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Qwen3Asr::Result Qwen3Asr::transcribe(const float * pcm, size_t nSamples)
|
||||
{
|
||||
Result res;
|
||||
|
||||
if (!d->model || !d->ctx || !d->mctx) {
|
||||
res.error = "模型未加载";
|
||||
return res;
|
||||
}
|
||||
if (nSamples == 0) {
|
||||
res.error = "音频为空";
|
||||
return res;
|
||||
}
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
// 每段独立转写,先清空 KV cache
|
||||
llama_memory_clear(llama_get_memory(d->ctx), true);
|
||||
|
||||
const std::string marker = mtmd_default_marker();
|
||||
const std::string prompt = d->buildPrompt(marker);
|
||||
|
||||
mtmd_bitmap * bitmap = mtmd_bitmap_init_from_audio(nSamples, pcm);
|
||||
if (!bitmap) {
|
||||
res.error = "构造音频 bitmap 失败";
|
||||
return res;
|
||||
}
|
||||
|
||||
mtmd_input_chunks * chunks = mtmd_input_chunks_init();
|
||||
const mtmd_input_text text{ prompt.c_str(), /*add_special*/ true, /*parse_special*/ true };
|
||||
const mtmd_bitmap * bitmaps[1] = { bitmap };
|
||||
|
||||
const int32_t tokRes = mtmd_tokenize(d->mctx, chunks, &text, bitmaps, 1);
|
||||
if (tokRes != 0) {
|
||||
mtmd_bitmap_free(bitmap);
|
||||
mtmd_input_chunks_free(chunks);
|
||||
res.error = "mtmd_tokenize 失败 (code " + std::to_string(tokRes) + ")";
|
||||
return res;
|
||||
}
|
||||
|
||||
llama_pos nPast = 0;
|
||||
const int32_t evalRes = mtmd_helper_eval_chunks(
|
||||
d->mctx, d->ctx, chunks,
|
||||
/*n_past*/ 0, /*seq_id*/ 0, /*n_batch*/ d->opt.nBatch,
|
||||
/*logits_last*/ true, &nPast);
|
||||
mtmd_bitmap_free(bitmap);
|
||||
if (evalRes != 0) {
|
||||
mtmd_input_chunks_free(chunks);
|
||||
res.error = "mtmd_helper_eval_chunks 失败 (code " + std::to_string(evalRes) + ")";
|
||||
return res;
|
||||
}
|
||||
mtmd_input_chunks_free(chunks);
|
||||
|
||||
// 贪心解码
|
||||
llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
|
||||
llama_sampler_chain_add(smpl, llama_sampler_init_greedy());
|
||||
|
||||
std::string out;
|
||||
for (int i = 0; i < d->opt.maxTokens; ++i) {
|
||||
llama_token id = llama_sampler_sample(smpl, d->ctx, -1);
|
||||
if (llama_vocab_is_eog(d->vocab, id)) break;
|
||||
|
||||
char buf[256];
|
||||
const int32_t n = llama_token_to_piece(d->vocab, id, buf, sizeof(buf), 0, /*special*/ true);
|
||||
if (n > 0) out.append(buf, (size_t) n);
|
||||
++res.tokenCount;
|
||||
|
||||
llama_batch batch = llama_batch_get_one(&id, 1);
|
||||
if (llama_decode(d->ctx, batch) != 0) {
|
||||
res.error = "llama_decode 失败";
|
||||
break;
|
||||
}
|
||||
}
|
||||
llama_sampler_free(smpl);
|
||||
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
res.inferSeconds = std::chrono::duration<double>(t1 - t0).count();
|
||||
res.raw = out;
|
||||
res.transcript = parseAsrOutput(out);
|
||||
res.ok = res.error.empty();
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -1,54 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
|
||||
#include "transcript.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
struct AsrOptions {
|
||||
std::string modelPath; // Qwen3-ASR 主模型 GGUF(架构须为 qwen3vl)
|
||||
std::string mmprojPath; // 音频编码器 mmproj GGUF(clip + qwen3a)
|
||||
int threads = 8;
|
||||
int nCtx = 4096;
|
||||
int nBatch = 4096;
|
||||
int nUbatch = 1024;
|
||||
int maxTokens = 256; // 单段最多生成多少 token
|
||||
bool warmup = false; // mtmd 初始化后是否跑一次预热编码
|
||||
bool verbose = false;
|
||||
};
|
||||
|
||||
// 进程内 Qwen3-ASR 推理封装(libllama + libmtmd)。
|
||||
// 模型常驻,可反复 transcribe();每次调用会清空 KV cache。
|
||||
class Qwen3Asr {
|
||||
public:
|
||||
Qwen3Asr();
|
||||
~Qwen3Asr();
|
||||
|
||||
Qwen3Asr(const Qwen3Asr &) = delete;
|
||||
Qwen3Asr & operator=(const Qwen3Asr &) = delete;
|
||||
|
||||
bool load(const AsrOptions & opt, std::string * error);
|
||||
|
||||
// 期望的输入采样率(Qwen3-ASR 为 16000)
|
||||
int sampleRate() const;
|
||||
|
||||
struct Result {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
ParsedTranscript transcript; // 已拆出 language / text
|
||||
std::string raw; // 模型原始输出,便于排查
|
||||
double inferSeconds = 0.0;
|
||||
int tokenCount = 0;
|
||||
};
|
||||
|
||||
// pcm: 单声道 float32 [-1,1],采样率为 sampleRate()
|
||||
Result transcribe(const float * pcm, size_t nSamples);
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
Impl * d = nullptr;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,96 @@
|
||||
#include "appsettings.h"
|
||||
|
||||
#include <QSettings>
|
||||
|
||||
namespace lc {
|
||||
|
||||
AppSettings & AppSettings::instance()
|
||||
{
|
||||
static AppSettings s;
|
||||
return s;
|
||||
}
|
||||
|
||||
void AppSettings::load()
|
||||
{
|
||||
QSettings s;
|
||||
s.beginGroup(QStringLiteral("app"));
|
||||
modelId = s.value(QStringLiteral("modelId")).toString();
|
||||
language = s.value(QStringLiteral("language")).toString();
|
||||
|
||||
opacityPercent = s.value(QStringLiteral("opacity"), 84).toInt();
|
||||
fontSize = s.value(QStringLiteral("fontSize"), 15).toInt();
|
||||
showUnstableTail = s.value(QStringLiteral("showUnstableTail"), true).toBool();
|
||||
collapsedLines = s.value(QStringLiteral("collapsedLines"), 2).toInt();
|
||||
expandedLines = s.value(QStringLiteral("expandedLines"), 8).toInt();
|
||||
|
||||
hasWindowPos = s.contains(QStringLiteral("windowX"));
|
||||
if (hasWindowPos) {
|
||||
windowPos = QPoint(s.value(QStringLiteral("windowX")).toInt(),
|
||||
s.value(QStringLiteral("windowY")).toInt());
|
||||
}
|
||||
|
||||
captureDevice = s.value(QStringLiteral("captureDevice")).toString();
|
||||
|
||||
mirrorBase = s.value(QStringLiteral("mirrorBase"),
|
||||
QStringLiteral("https://hf-mirror.com")).toString();
|
||||
proxyMode = s.value(QStringLiteral("proxyMode"), 0).toInt();
|
||||
proxyHost = s.value(QStringLiteral("proxyHost")).toString();
|
||||
proxyPort = s.value(QStringLiteral("proxyPort"), 0).toInt();
|
||||
proxyUser = s.value(QStringLiteral("proxyUser")).toString();
|
||||
proxyPass = s.value(QStringLiteral("proxyPass")).toString();
|
||||
|
||||
chunkSec = s.value(QStringLiteral("chunkSec"), 0.0).toDouble();
|
||||
threads = s.value(QStringLiteral("threads"), 8).toInt();
|
||||
|
||||
streamMode = s.value(QStringLiteral("streamMode"), QStringLiteral("incremental")).toString();
|
||||
streamWindowSec = s.value(QStringLiteral("streamWindowSec"), 16.0).toDouble();
|
||||
streamSegmentSec = s.value(QStringLiteral("streamSegmentSec"), 30.0).toDouble();
|
||||
unfixedTokens = s.value(QStringLiteral("unfixedTokens"), 5).toInt();
|
||||
unfixedChunks = s.value(QStringLiteral("unfixedChunks"), 2).toInt();
|
||||
maxTokens = s.value(QStringLiteral("maxTokens"), 256).toInt();
|
||||
verbose = s.value(QStringLiteral("verbose"), false).toBool();
|
||||
modelDir = s.value(QStringLiteral("modelDir")).toString();
|
||||
s.endGroup();
|
||||
}
|
||||
|
||||
void AppSettings::save()
|
||||
{
|
||||
QSettings s;
|
||||
s.beginGroup(QStringLiteral("app"));
|
||||
s.setValue(QStringLiteral("modelId"), modelId);
|
||||
s.setValue(QStringLiteral("language"), language);
|
||||
|
||||
s.setValue(QStringLiteral("opacity"), opacityPercent);
|
||||
s.setValue(QStringLiteral("fontSize"), fontSize);
|
||||
s.setValue(QStringLiteral("showUnstableTail"), showUnstableTail);
|
||||
s.setValue(QStringLiteral("collapsedLines"), collapsedLines);
|
||||
s.setValue(QStringLiteral("expandedLines"), expandedLines);
|
||||
|
||||
if (hasWindowPos) {
|
||||
s.setValue(QStringLiteral("windowX"), windowPos.x());
|
||||
s.setValue(QStringLiteral("windowY"), windowPos.y());
|
||||
}
|
||||
|
||||
s.setValue(QStringLiteral("captureDevice"), captureDevice);
|
||||
s.setValue(QStringLiteral("mirrorBase"), mirrorBase);
|
||||
s.setValue(QStringLiteral("proxyMode"), proxyMode);
|
||||
s.setValue(QStringLiteral("proxyHost"), proxyHost);
|
||||
s.setValue(QStringLiteral("proxyPort"), proxyPort);
|
||||
s.setValue(QStringLiteral("proxyUser"), proxyUser);
|
||||
s.setValue(QStringLiteral("proxyPass"), proxyPass);
|
||||
|
||||
s.setValue(QStringLiteral("chunkSec"), chunkSec);
|
||||
s.setValue(QStringLiteral("threads"), threads);
|
||||
s.setValue(QStringLiteral("streamMode"), streamMode);
|
||||
s.setValue(QStringLiteral("streamWindowSec"), streamWindowSec);
|
||||
s.setValue(QStringLiteral("streamSegmentSec"), streamSegmentSec);
|
||||
s.setValue(QStringLiteral("unfixedTokens"), unfixedTokens);
|
||||
s.setValue(QStringLiteral("unfixedChunks"), unfixedChunks);
|
||||
s.setValue(QStringLiteral("maxTokens"), maxTokens);
|
||||
s.setValue(QStringLiteral("verbose"), verbose);
|
||||
s.setValue(QStringLiteral("modelDir"), modelDir);
|
||||
s.endGroup();
|
||||
s.sync();
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include <QPoint>
|
||||
#include <QString>
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 应用配置(QSettings)。GUI 完全靠它驱动,不再依赖命令行参数;
|
||||
// 命令行显式给出的值会覆盖这里的值(自动化测试用)。
|
||||
class AppSettings {
|
||||
public:
|
||||
static AppSettings & instance();
|
||||
|
||||
// 模型
|
||||
QString modelId; // 当前使用的模型注册表 id
|
||||
QString language; // 识别语言提示;"" = 自动
|
||||
|
||||
// 显示
|
||||
int opacityPercent = 84;
|
||||
int fontSize = 15;
|
||||
bool showUnstableTail = true;
|
||||
int collapsedLines = 2;
|
||||
int expandedLines = 8;
|
||||
|
||||
// 窗口
|
||||
QPoint windowPos; // 空 = 默认(屏幕下方居中)
|
||||
bool hasWindowPos = false;
|
||||
|
||||
// 采集
|
||||
QString captureDevice; // 空 = 跟随系统默认输出
|
||||
|
||||
// 下载
|
||||
QString mirrorBase = QStringLiteral("https://hf-mirror.com");
|
||||
int proxyMode = 0; // 0=不使用 1=跟随系统 2=手动
|
||||
QString proxyHost;
|
||||
int proxyPort = 0;
|
||||
QString proxyUser;
|
||||
QString proxyPass;
|
||||
|
||||
// 高级
|
||||
double chunkSec = 0.0; // 0 = 由后端决定
|
||||
int threads = 8;
|
||||
|
||||
// 高级:流式参数(只影响 llama 后端的 Qwen3-ASR;流式 ONNX 只用 chunkSec)
|
||||
QString streamMode = QStringLiteral("incremental"); // incremental | append | window
|
||||
double streamWindowSec = 16.0; // 仅 window 模式:滑窗上限;0 = 不限
|
||||
double streamSegmentSec = 30.0; // 单段最长时长;0 = 不限
|
||||
int unfixedTokens = 5; // 前缀回滚丢弃的 token 数(算作不稳定尾部)
|
||||
int unfixedChunks = 2; // 冷启动不带前缀的 chunk 数
|
||||
int maxTokens = 256; // 单段最多生成 token 数
|
||||
|
||||
// 高级:调试
|
||||
bool verbose = false; // 输出 llama.cpp / mtmd 的详细日志
|
||||
QString modelDir; // 空 = 默认模型存储目录
|
||||
|
||||
void load();
|
||||
void save();
|
||||
|
||||
private:
|
||||
AppSettings() = default;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,276 @@
|
||||
#include "captionwindow.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QFontMetrics>
|
||||
#include <QHBoxLayout>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QPushButton>
|
||||
#include <QScreen>
|
||||
#include <QTextCursor>
|
||||
#include <QTextEdit>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kCollapsedLines = 2;
|
||||
constexpr int kExpandedLines = 8;
|
||||
constexpr int kMargin = 12;
|
||||
constexpr int kTopRowHeight = 30; // 与关闭按钮一致
|
||||
constexpr int kRadius = 10;
|
||||
|
||||
QString escapeHtml(const QString & s)
|
||||
{
|
||||
return s.toHtmlEscaped().replace(QLatin1Char('\n'), QLatin1String("<br/>"));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CaptionWindow::CaptionWindow(QWidget * parent)
|
||||
: QWidget(parent)
|
||||
{
|
||||
// 无边框 + 置顶 + 不抢焦点(X11 下都有对应实现)
|
||||
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool
|
||||
| Qt::WindowDoesNotAcceptFocus);
|
||||
setAttribute(Qt::WA_TranslucentBackground);
|
||||
setAttribute(Qt::WA_ShowWithoutActivating);
|
||||
setWindowTitle(QStringLiteral("实时字幕"));
|
||||
|
||||
auto * root = new QVBoxLayout(this);
|
||||
root->setContentsMargins(kMargin, kMargin, kMargin, kMargin);
|
||||
root->setSpacing(6);
|
||||
|
||||
// ---- 顶部:语言标签 + 关闭 ----
|
||||
auto * top = new QHBoxLayout();
|
||||
top->setSpacing(6);
|
||||
|
||||
langPill_ = new QPushButton(this);
|
||||
langPill_->setCursor(Qt::PointingHandCursor);
|
||||
langPill_->setFocusPolicy(Qt::NoFocus);
|
||||
langPill_->setToolTip(tr("识别语言(设置界面将在后续阶段接入)"));
|
||||
connect(langPill_, &QPushButton::clicked, this, &CaptionWindow::languageClicked);
|
||||
|
||||
closeBtn_ = new QPushButton(QStringLiteral("\u2715"), this); // ✕
|
||||
closeBtn_->setObjectName(QStringLiteral("closeBtn"));
|
||||
closeBtn_->setCursor(Qt::PointingHandCursor);
|
||||
closeBtn_->setFocusPolicy(Qt::NoFocus);
|
||||
closeBtn_->setFixedSize(30, 30); // 原来 22×22 太小,不好点
|
||||
connect(closeBtn_, &QPushButton::clicked, this, &CaptionWindow::closed);
|
||||
|
||||
top->addWidget(langPill_);
|
||||
top->addStretch(1);
|
||||
top->addWidget(closeBtn_);
|
||||
root->addLayout(top);
|
||||
|
||||
// ---- 中间:字幕文本 ----
|
||||
text_ = new QTextEdit(this);
|
||||
text_->setReadOnly(true);
|
||||
text_->setFrameShape(QFrame::NoFrame);
|
||||
text_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
text_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
text_->setTextInteractionFlags(Qt::NoTextInteraction); // 让拖动可以穿透到窗口
|
||||
text_->setFocusPolicy(Qt::NoFocus);
|
||||
text_->viewport()->setAutoFillBackground(false);
|
||||
root->addWidget(text_, 1);
|
||||
|
||||
// ---- 底部:展开/收起 ----
|
||||
toggleBtn_ = new QPushButton(this);
|
||||
toggleBtn_->setCursor(Qt::PointingHandCursor);
|
||||
toggleBtn_->setFocusPolicy(Qt::NoFocus);
|
||||
connect(toggleBtn_, &QPushButton::clicked, this, [this] { setCollapsed(!collapsed_); });
|
||||
|
||||
auto * bottom = new QHBoxLayout();
|
||||
bottom->addStretch(1);
|
||||
bottom->addWidget(toggleBtn_);
|
||||
bottom->addStretch(1);
|
||||
root->addLayout(bottom);
|
||||
|
||||
setStyleSheet(QString()); // 实际样式由 applyStyle() 生成(透明度可调)
|
||||
applyStyle();
|
||||
|
||||
langPill_->setObjectName(QStringLiteral("langPill"));
|
||||
toggleBtn_->setObjectName(QStringLiteral("toggleBtn"));
|
||||
|
||||
relayout();
|
||||
setLanguage(QString());
|
||||
setCaption(QString(), QString());
|
||||
|
||||
// 默认停在主屏下方居中
|
||||
if (QScreen * screen = QApplication::primaryScreen()) {
|
||||
const QRect avail = screen->availableGeometry();
|
||||
const int w = qMin(900, (int) (avail.width() * 0.72));
|
||||
resize(w, height());
|
||||
move(avail.center().x() - w / 2, avail.bottom() - height() - 48);
|
||||
}
|
||||
}
|
||||
|
||||
void CaptionWindow::applyStyle()
|
||||
{
|
||||
// 注意:这里不设 CaptionWindow 自己的 background。
|
||||
// 自定义 QWidget 子类默认不绘制样式表背景,而且带 WA_TranslucentBackground 的
|
||||
// 顶层窗口本来就该自己画底板 —— 见 paintEvent()。
|
||||
setStyleSheet(QStringLiteral(R"(
|
||||
QPushButton {
|
||||
color: #f0f0f0;
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
padding: 2px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
QPushButton:hover { background-color: rgba(255,255,255,40); border-radius: 9px; }
|
||||
#langPill {
|
||||
border: 1px solid rgba(255,255,255,140);
|
||||
border-radius: 10px;
|
||||
padding: 1px 10px;
|
||||
}
|
||||
#toggleBtn { color: #bbbbbb; font-size: 15px; padding: 0px; }
|
||||
#closeBtn {
|
||||
color: #e8e8e8;
|
||||
font-size: 16px;
|
||||
padding: 0px;
|
||||
border-radius: 15px;
|
||||
}
|
||||
#closeBtn:hover { background-color: rgba(255,90,90,120); }
|
||||
QTextEdit {
|
||||
color: #ffffff;
|
||||
background: transparent;
|
||||
font-size: %1px;
|
||||
}
|
||||
)").arg(fontSize_));
|
||||
}
|
||||
|
||||
void CaptionWindow::paintEvent(QPaintEvent *)
|
||||
{
|
||||
// 背景是"黑色 + 一定不透明度",不是全透明:这样才能保证任何桌面背景下文字都可读。
|
||||
const int alpha = qBound(20, opacityPercent_, 100) * 255 / 100;
|
||||
|
||||
QPainter p(this);
|
||||
p.setRenderHint(QPainter::Antialiasing, true);
|
||||
p.setPen(Qt::NoPen);
|
||||
p.setBrush(QColor(0, 0, 0, alpha));
|
||||
p.drawRoundedRect(rect(), kRadius, kRadius);
|
||||
}
|
||||
|
||||
void CaptionWindow::setTextFontSize(int px)
|
||||
{
|
||||
fontSize_ = qBound(9, px, 40);
|
||||
applyStyle();
|
||||
relayout();
|
||||
}
|
||||
|
||||
void CaptionWindow::setLineCounts(int collapsed, int expanded)
|
||||
{
|
||||
collapsedLines_ = qBound(1, collapsed, 6);
|
||||
expandedLines_ = qBound(collapsedLines_, expanded, 40);
|
||||
relayout();
|
||||
}
|
||||
|
||||
void CaptionWindow::setShowTail(bool on)
|
||||
{
|
||||
if (showTail_ == on) return;
|
||||
showTail_ = on;
|
||||
renderCaption(); // 用缓存的文本立刻重画(不能走 setCaption:参数没变会被早退)
|
||||
}
|
||||
|
||||
void CaptionWindow::setPanelOpacity(int percent)
|
||||
{
|
||||
const int clamped = qBound(20, percent, 100);
|
||||
if (clamped == opacityPercent_) return;
|
||||
opacityPercent_ = clamped;
|
||||
applyStyle();
|
||||
}
|
||||
|
||||
int CaptionWindow::lineHeight() const
|
||||
{
|
||||
return QFontMetrics(text_->font()).lineSpacing();
|
||||
}
|
||||
|
||||
int CaptionWindow::textHeight() const
|
||||
{
|
||||
return lineHeight() * (collapsed_ ? collapsedLines_ : expandedLines_)
|
||||
+ (int) text_->document()->documentMargin() * 2;
|
||||
}
|
||||
|
||||
void CaptionWindow::relayout()
|
||||
{
|
||||
text_->setFixedHeight(textHeight());
|
||||
// 折叠态显示向下的箭头(点击展开),展开态显示向上的箭头(点击收起)
|
||||
toggleBtn_->setText(collapsed_ ? QStringLiteral("\u2304") // ⌄
|
||||
: QStringLiteral("\u2303")); // ⌃
|
||||
toggleBtn_->setToolTip(collapsed_ ? tr("展开") : tr("收起"));
|
||||
// 顶部那行的高度要跟着关闭按钮走,否则会挤到字幕
|
||||
const int h = kMargin * 2 + kTopRowHeight + 6 + textHeight() + 6 + 24;
|
||||
setFixedHeight(h);
|
||||
setMinimumWidth(320);
|
||||
scrollToEnd();
|
||||
}
|
||||
|
||||
void CaptionWindow::scrollToEnd()
|
||||
{
|
||||
QTextCursor c = text_->textCursor();
|
||||
c.movePosition(QTextCursor::End);
|
||||
text_->setTextCursor(c);
|
||||
text_->ensureCursorVisible();
|
||||
}
|
||||
|
||||
void CaptionWindow::setCollapsed(bool collapsed)
|
||||
{
|
||||
if (collapsed_ == collapsed) return;
|
||||
collapsed_ = collapsed;
|
||||
relayout();
|
||||
}
|
||||
|
||||
void CaptionWindow::setLanguage(const QString & language)
|
||||
{
|
||||
language_ = language;
|
||||
langPill_->setText(language.isEmpty() ? tr("自动") : language);
|
||||
langPill_->adjustSize();
|
||||
}
|
||||
|
||||
void CaptionWindow::setCaption(const QString & committed, const QString & tail)
|
||||
{
|
||||
if (committed == committed_ && tail == tail_) return;
|
||||
committed_ = committed;
|
||||
tail_ = tail;
|
||||
renderCaption();
|
||||
}
|
||||
|
||||
// 已稳定部分正常色,不稳定尾部暗色 —— 和 CLI 版渲染一致
|
||||
void CaptionWindow::renderCaption()
|
||||
{
|
||||
const QString html =
|
||||
showTail_
|
||||
? QStringLiteral("<div>%1<span style=\"color:#9a9a9a\">%2</span></div>")
|
||||
.arg(escapeHtml(committed_), escapeHtml(tail_))
|
||||
: QStringLiteral("<div>%1</div>").arg(escapeHtml(committed_));
|
||||
text_->setHtml(html);
|
||||
scrollToEnd();
|
||||
}
|
||||
|
||||
void CaptionWindow::mousePressEvent(QMouseEvent * e)
|
||||
{
|
||||
if (e->button() == Qt::LeftButton) {
|
||||
dragging_ = true;
|
||||
dragOffset_ = e->globalPosition().toPoint() - frameGeometry().topLeft();
|
||||
e->accept();
|
||||
}
|
||||
}
|
||||
|
||||
void CaptionWindow::mouseMoveEvent(QMouseEvent * e)
|
||||
{
|
||||
if (dragging_ && (e->buttons() & Qt::LeftButton)) {
|
||||
move(e->globalPosition().toPoint() - dragOffset_);
|
||||
e->accept();
|
||||
}
|
||||
}
|
||||
|
||||
void CaptionWindow::mouseReleaseEvent(QMouseEvent * e)
|
||||
{
|
||||
if (dragging_) Q_EMIT moved(pos());
|
||||
dragging_ = false;
|
||||
e->accept();
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <QPoint>
|
||||
#include <QWidget>
|
||||
|
||||
class QLabel;
|
||||
class QPushButton;
|
||||
class QTextEdit;
|
||||
|
||||
namespace lc {
|
||||
|
||||
// 悬浮字幕窗(对应 Chrome 实时字幕那种样式):
|
||||
// 无边框、置顶、不接受焦点;折叠时两行,展开后多行。
|
||||
class CaptionWindow : public QWidget {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit CaptionWindow(QWidget * parent = nullptr);
|
||||
|
||||
// committed 为已稳定文本,tail 为不稳定尾部(暗色显示)
|
||||
void setCaption(const QString & committed, const QString & tail);
|
||||
void setLanguage(const QString & language);
|
||||
|
||||
bool isCollapsed() const { return collapsed_; }
|
||||
void setCollapsed(bool collapsed);
|
||||
|
||||
// 背景不透明度(百分比)。范围限制在 20~100:
|
||||
// 太低会让字幕在任何桌面背景下都读不清,所以不给到全透明。
|
||||
void setPanelOpacity(int percent);
|
||||
int panelOpacity() const { return opacityPercent_; }
|
||||
|
||||
void setTextFontSize(int px);
|
||||
void setLineCounts(int collapsed, int expanded);
|
||||
void setShowTail(bool on);
|
||||
|
||||
Q_SIGNALS:
|
||||
void languageClicked();
|
||||
void closed();
|
||||
void moved(const QPoint & topLeft);
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QMouseEvent * e) override;
|
||||
void mouseMoveEvent(QMouseEvent * e) override;
|
||||
void mouseReleaseEvent(QMouseEvent * e) override;
|
||||
void paintEvent(QPaintEvent * e) override;
|
||||
|
||||
private:
|
||||
int lineHeight() const;
|
||||
int textHeight() const; // 按折叠/展开计算文本区高度
|
||||
void relayout();
|
||||
void scrollToEnd();
|
||||
void renderCaption(); // 按 showTail_ 重画缓存的文本
|
||||
void applyStyle();
|
||||
|
||||
QPushButton * langPill_ = nullptr;
|
||||
QPushButton * closeBtn_ = nullptr;
|
||||
QPushButton * toggleBtn_ = nullptr;
|
||||
QTextEdit * text_ = nullptr;
|
||||
|
||||
bool collapsed_ = true;
|
||||
bool showTail_ = true;
|
||||
int fontSize_ = 15;
|
||||
int collapsedLines_ = 2;
|
||||
int expandedLines_ = 8;
|
||||
int opacityPercent_ = 84; // 背景不透明度(百分比)
|
||||
bool dragging_ = false;
|
||||
QPoint dragOffset_;
|
||||
QString language_;
|
||||
QString committed_;
|
||||
QString tail_;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "livetranscriber.h"
|
||||
|
||||
#include "iasr.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
LiveTranscriber::LiveTranscriber(QObject * parent) : QObject(parent) {}
|
||||
|
||||
LiveTranscriber::~LiveTranscriber()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
QString LiveTranscriber::deviceName() const
|
||||
{
|
||||
return pipeline_ ? QString::fromStdString(pipeline_->deviceName()) : QString();
|
||||
}
|
||||
|
||||
bool LiveTranscriber::start(IAsr & asr, const StreamOptions & opts, QString * error)
|
||||
{
|
||||
stop();
|
||||
|
||||
LivePipelineOptions popt;
|
||||
popt.stream = opts;
|
||||
popt.captureDevice = captureDevice_;
|
||||
|
||||
pipeline_ = std::make_unique<LivePipeline>(asr, popt);
|
||||
|
||||
// 回调在工作线程上被调用;连到主线程的接收者时 Qt 会自动排队投递。
|
||||
pipeline_->setCaptionCallback([this](const std::string & committed,
|
||||
const std::string & tail,
|
||||
const std::string & language) {
|
||||
Q_EMIT caption(QString::fromStdString(committed),
|
||||
QString::fromStdString(tail),
|
||||
QString::fromStdString(language));
|
||||
});
|
||||
pipeline_->setErrorCallback([this](const std::string & message) {
|
||||
Q_EMIT failed(QString::fromStdString(message));
|
||||
});
|
||||
|
||||
std::string err;
|
||||
if (!pipeline_->start(&err)) {
|
||||
if (error) *error = QString::fromStdString(err);
|
||||
pipeline_.reset();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void LiveTranscriber::stop()
|
||||
{
|
||||
if (pipeline_) {
|
||||
pipeline_->stop();
|
||||
pipeline_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include "livepipeline.h"
|
||||
#include "streamingasr.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
class IAsr;
|
||||
|
||||
// LivePipeline 的 Qt 适配器:只负责把 std::function 回调转成 Qt 信号,
|
||||
// 真正的逻辑都在 core 里(所以那些逻辑可以脱离 UI 单独测试)。
|
||||
class LiveTranscriber : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit LiveTranscriber(QObject * parent = nullptr);
|
||||
~LiveTranscriber() override;
|
||||
|
||||
// 后端在 start 时注入:设置里换了模型就 stop() 再 start()
|
||||
// 采集源:空 = 跟随系统默认输出
|
||||
void setCaptureDevice(const QString & sink) { captureDevice_ = sink.toStdString(); }
|
||||
|
||||
bool start(IAsr & asr, const StreamOptions & opts, QString * error = nullptr);
|
||||
void stop();
|
||||
|
||||
QString deviceName() const;
|
||||
|
||||
Q_SIGNALS:
|
||||
// committed = 已稳定文本;tail = 不稳定尾部(UI 用暗色显示)
|
||||
void caption(const QString & committed, const QString & tail, const QString & language);
|
||||
void failed(const QString & message);
|
||||
|
||||
private:
|
||||
std::string captureDevice_;
|
||||
std::unique_ptr<LivePipeline> pipeline_;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
|
||||
@@ -0,0 +1,627 @@
|
||||
#include "settingsdialog.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDesktopServices>
|
||||
#include <QDir>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFileInfo>
|
||||
#include <QFormLayout>
|
||||
#include <QGroupBox>
|
||||
#include <QHeaderView>
|
||||
#include <QHBoxLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QNetworkProxy>
|
||||
#include <QProgressBar>
|
||||
#include <QPushButton>
|
||||
#include <QSlider>
|
||||
#include <QSpinBox>
|
||||
#include <QTabWidget>
|
||||
#include <QTableWidget>
|
||||
#include <QUrl>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include "appsettings.h"
|
||||
#include "audio.h"
|
||||
#include "modeldownloader.h"
|
||||
#include "modelstore.h"
|
||||
#include "transcript.h"
|
||||
|
||||
namespace lc {
|
||||
|
||||
using models::ModelStore;
|
||||
using models::ModelInfo;
|
||||
using models::ModelDownloader;
|
||||
|
||||
SettingsDialog::SettingsDialog(bool firstRun, QWidget * parent)
|
||||
: QDialog(parent), downloader_(new ModelDownloader(this)), firstRun_(firstRun)
|
||||
{
|
||||
setWindowTitle(firstRun ? tr("实时字幕 — 首次配置") : tr("实时字幕 — 设置"));
|
||||
setMinimumSize(620, 520);
|
||||
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
|
||||
auto * tabs = new QTabWidget(this);
|
||||
tabs->addTab(buildModelPage(), tr("模型"));
|
||||
tabs->addTab(buildDisplayPage(), tr("显示"));
|
||||
tabs->addTab(buildAdvancedPage(), tr("高级"));
|
||||
|
||||
auto * hint = new QLabel(this);
|
||||
hint->setWordWrap(true);
|
||||
hint->setText(firstRun ? tr("首次使用请先下载一个模型(中文/日文建议选流式模型,通用场景选 Qwen3-ASR)。")
|
||||
: QString());
|
||||
|
||||
auto * okBtn = new QPushButton(tr("确定"), this);
|
||||
auto * applyBtn = new QPushButton(tr("应用"), this);
|
||||
auto * cancelBtn = new QPushButton(tr("取消"), this);
|
||||
okBtn->setDefault(true);
|
||||
okBtn->setToolTip(tr("应用并关闭"));
|
||||
applyBtn->setToolTip(tr("应用但不关闭,方便预览效果"));
|
||||
connect(okBtn, &QPushButton::clicked, this, &SettingsDialog::onAccept);
|
||||
connect(applyBtn, &QPushButton::clicked, this, &SettingsDialog::onApplyClicked);
|
||||
connect(cancelBtn, &QPushButton::clicked, this, &QDialog::reject);
|
||||
|
||||
auto * buttons = new QHBoxLayout;
|
||||
buttons->addStretch(1);
|
||||
buttons->addWidget(applyBtn);
|
||||
buttons->addWidget(cancelBtn);
|
||||
buttons->addWidget(okBtn);
|
||||
|
||||
auto * root = new QVBoxLayout(this);
|
||||
root->addWidget(tabs, 1);
|
||||
if (!hint->text().isEmpty()) root->addWidget(hint);
|
||||
root->addLayout(buttons);
|
||||
Q_UNUSED(cfg);
|
||||
|
||||
refreshModelTable();
|
||||
refreshActiveCombo();
|
||||
rebuildLanguageCombo();
|
||||
updateStreamGroupEnabled();
|
||||
}
|
||||
|
||||
SettingsDialog::~SettingsDialog() = default;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
QWidget * SettingsDialog::buildModelPage()
|
||||
{
|
||||
auto * page = new QWidget(this);
|
||||
auto * root = new QVBoxLayout(page);
|
||||
|
||||
table_ = new QTableWidget(page);
|
||||
table_->setColumnCount(4);
|
||||
table_->setHorizontalHeaderLabels({tr("模型"), tr("语言"), tr("许可"), tr("状态")});
|
||||
table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
|
||||
for (int c = 1; c < 4; ++c) {
|
||||
table_->horizontalHeader()->setSectionResizeMode(c, QHeaderView::ResizeToContents);
|
||||
}
|
||||
table_->setSelectionBehavior(QAbstractItemView::SelectRows);
|
||||
table_->setSelectionMode(QAbstractItemView::SingleSelection);
|
||||
table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
table_->verticalHeader()->setVisible(false);
|
||||
root->addWidget(table_, 1);
|
||||
|
||||
auto * btnRow = new QHBoxLayout;
|
||||
downloadBtn_ = new QPushButton(tr("下载"), page);
|
||||
deleteBtn_ = new QPushButton(tr("删除"), page);
|
||||
verifyBtn_ = new QPushButton(tr("校验完整性"), page);
|
||||
auto * openBtn = new QPushButton(tr("打开模型目录"), page);
|
||||
btnRow->addWidget(downloadBtn_);
|
||||
btnRow->addWidget(verifyBtn_);
|
||||
btnRow->addWidget(deleteBtn_);
|
||||
btnRow->addWidget(openBtn);
|
||||
btnRow->addStretch(1);
|
||||
root->addLayout(btnRow);
|
||||
|
||||
connect(downloadBtn_, &QPushButton::clicked, this, &SettingsDialog::onDownload);
|
||||
connect(verifyBtn_, &QPushButton::clicked, this, &SettingsDialog::onVerify);
|
||||
connect(deleteBtn_, &QPushButton::clicked, this, &SettingsDialog::onDelete);
|
||||
connect(openBtn, &QPushButton::clicked, this, &SettingsDialog::onOpenDir);
|
||||
|
||||
progress_ = new QProgressBar(page);
|
||||
progress_->setVisible(false);
|
||||
statusLabel_ = new QLabel(page);
|
||||
root->addWidget(progress_);
|
||||
root->addWidget(statusLabel_);
|
||||
|
||||
auto * form = new QFormLayout;
|
||||
captureCombo_ = new QComboBox(page);
|
||||
captureCombo_->addItem(tr("跟随系统默认输出"), QString());
|
||||
{
|
||||
std::string derr;
|
||||
for (const auto & dev : lc::listOutputDevices(&derr)) {
|
||||
captureCombo_->addItem(QString::fromStdString(dev.description) +
|
||||
(dev.isDefault ? tr("(默认)") : QString()),
|
||||
QString::fromStdString(dev.sink));
|
||||
}
|
||||
}
|
||||
{
|
||||
const int idx = captureCombo_->findData(AppSettings::instance().captureDevice);
|
||||
if (idx >= 0) captureCombo_->setCurrentIndex(idx);
|
||||
}
|
||||
form->addRow(tr("采集设备"), captureCombo_);
|
||||
|
||||
activeCombo_ = new QComboBox(page);
|
||||
form->addRow(tr("当前使用"), activeCombo_);
|
||||
|
||||
languageCombo_ = new QComboBox(page);
|
||||
languageCombo_->setToolTip(tr("多语言模型(Nemotron / Qwen3-ASR)用它指定语言;"
|
||||
"列表按所选模型支持的语言变化。"));
|
||||
form->addRow(tr("识别语言"), languageCombo_);
|
||||
|
||||
mirrorEdit_ = new QLineEdit(page);
|
||||
mirrorEdit_->setPlaceholderText(QStringLiteral("https://hf-mirror.com"));
|
||||
form->addRow(tr("下载源"), mirrorEdit_);
|
||||
|
||||
proxyCombo_ = new QComboBox(page);
|
||||
proxyCombo_->addItem(tr("不使用代理"), 0);
|
||||
proxyCombo_->addItem(tr("跟随系统"), 1);
|
||||
proxyCombo_->addItem(tr("手动设置"), 2);
|
||||
proxyHost_ = new QLineEdit(page);
|
||||
proxyHost_->setPlaceholderText(tr("主机"));
|
||||
proxyPort_ = new QSpinBox(page);
|
||||
proxyPort_->setRange(0, 65535);
|
||||
proxyUser_ = new QLineEdit(page);
|
||||
proxyUser_->setPlaceholderText(tr("用户名(可选)"));
|
||||
proxyPass_ = new QLineEdit(page);
|
||||
proxyPass_->setEchoMode(QLineEdit::Password);
|
||||
proxyPass_->setPlaceholderText(tr("密码(可选)"));
|
||||
|
||||
auto * proxyRow = new QWidget(page);
|
||||
auto * proxyLay = new QHBoxLayout(proxyRow);
|
||||
proxyLay->setContentsMargins(0, 0, 0, 0);
|
||||
proxyLay->addWidget(proxyCombo_);
|
||||
proxyLay->addWidget(proxyHost_);
|
||||
proxyLay->addWidget(proxyPort_);
|
||||
form->addRow(tr("代理"), proxyRow);
|
||||
form->addRow(QString(), proxyUser_);
|
||||
form->addRow(QString(), proxyPass_);
|
||||
|
||||
root->addLayout(form);
|
||||
|
||||
const auto updateProxyEnabled = [this] {
|
||||
const bool manual = proxyCombo_->currentData().toInt() == 2;
|
||||
proxyHost_->setEnabled(manual);
|
||||
proxyPort_->setEnabled(manual);
|
||||
proxyUser_->setEnabled(manual);
|
||||
proxyPass_->setEnabled(manual);
|
||||
};
|
||||
connect(proxyCombo_, &QComboBox::currentIndexChanged, this,
|
||||
[updateProxyEnabled](int) { updateProxyEnabled(); });
|
||||
updateProxyEnabled();
|
||||
|
||||
// 回填已保存的设置
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
mirrorEdit_->setText(cfg.mirrorBase);
|
||||
proxyCombo_->setCurrentIndex(proxyCombo_->findData(cfg.proxyMode));
|
||||
proxyHost_->setText(cfg.proxyHost);
|
||||
proxyPort_->setValue(cfg.proxyPort);
|
||||
proxyUser_->setText(cfg.proxyUser);
|
||||
proxyPass_->setText(cfg.proxyPass);
|
||||
updateProxyEnabled();
|
||||
|
||||
connect(activeCombo_, &QComboBox::currentIndexChanged, this, [this](int idx) {
|
||||
if (idx >= 0) {
|
||||
AppSettings::instance().modelId = activeCombo_->itemData(idx).toString();
|
||||
AppSettings::instance().save();
|
||||
}
|
||||
rebuildLanguageCombo(); // 不同模型支持的语言不同
|
||||
updateStreamGroupEnabled();
|
||||
});
|
||||
|
||||
connect(downloader_, &ModelDownloader::status, this, [this](const QString & m) {
|
||||
statusLabel_->setText(m);
|
||||
});
|
||||
connect(downloader_, &ModelDownloader::progress, this,
|
||||
[this](const QString &, qint64 got, qint64 total) {
|
||||
progress_->setVisible(true);
|
||||
if (total > 0) {
|
||||
progress_->setRange(0, 100);
|
||||
progress_->setValue((int) (got * 100 / total));
|
||||
} else {
|
||||
progress_->setRange(0, 0); // 未知总量
|
||||
}
|
||||
});
|
||||
connect(downloader_, &ModelDownloader::finished, this,
|
||||
[this](bool ok, const QString & err) {
|
||||
progress_->setVisible(false);
|
||||
downloadBtn_->setEnabled(true);
|
||||
deleteBtn_->setEnabled(true);
|
||||
refreshModelTable();
|
||||
refreshActiveCombo();
|
||||
if (!ok && !err.isEmpty()) statusLabel_->setText(err);
|
||||
});
|
||||
return page;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
QWidget * SettingsDialog::buildDisplayPage()
|
||||
{
|
||||
auto * page = new QWidget(this);
|
||||
auto * form = new QFormLayout(page);
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
|
||||
fontSpin_ = new QSpinBox(page);
|
||||
fontSpin_->setRange(9, 40);
|
||||
fontSpin_->setValue(cfg.fontSize);
|
||||
form->addRow(tr("字号"), fontSpin_);
|
||||
|
||||
showTailCheck_ = new QCheckBox(tr("用灰色显示尚未稳定的尾部"), page);
|
||||
showTailCheck_->setChecked(cfg.showUnstableTail);
|
||||
form->addRow(QString(), showTailCheck_);
|
||||
|
||||
collapsedSpin_ = new QSpinBox(page);
|
||||
collapsedSpin_->setRange(1, 6);
|
||||
collapsedSpin_->setValue(cfg.collapsedLines);
|
||||
form->addRow(tr("折叠行数"), collapsedSpin_);
|
||||
|
||||
expandedSpin_ = new QSpinBox(page);
|
||||
expandedSpin_->setRange(2, 30);
|
||||
expandedSpin_->setValue(cfg.expandedLines);
|
||||
form->addRow(tr("展开行数"), expandedSpin_);
|
||||
|
||||
opacitySlider_ = new QSlider(Qt::Horizontal, page);
|
||||
opacitySlider_->setRange(20, 100);
|
||||
opacitySlider_->setValue(cfg.opacityPercent);
|
||||
opacityLabel_ = new QLabel(QStringLiteral("%1%").arg(cfg.opacityPercent), page);
|
||||
auto * opRow = new QWidget(page);
|
||||
auto * opLay = new QHBoxLayout(opRow);
|
||||
opLay->setContentsMargins(0, 0, 0, 0);
|
||||
opLay->addWidget(opacitySlider_, 1);
|
||||
opLay->addWidget(opacityLabel_);
|
||||
form->addRow(tr("背景不透明度"), opRow);
|
||||
connect(opacitySlider_, &QSlider::valueChanged, this, [this](int v) {
|
||||
opacityLabel_->setText(QStringLiteral("%1%").arg(v));
|
||||
});
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
QWidget * SettingsDialog::buildAdvancedPage()
|
||||
{
|
||||
auto * page = new QWidget(this);
|
||||
auto * root = new QVBoxLayout(page);
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
|
||||
// ---- 通用 ----
|
||||
auto * generalForm = new QFormLayout;
|
||||
|
||||
chunkSpin_ = new QDoubleSpinBox(page);
|
||||
chunkSpin_->setRange(0.0, 5.0);
|
||||
chunkSpin_->setSingleStep(0.1);
|
||||
chunkSpin_->setDecimals(2);
|
||||
chunkSpin_->setSpecialValueText(tr("自动"));
|
||||
chunkSpin_->setValue(cfg.chunkSec);
|
||||
chunkSpin_->setToolTip(tr("累积多少秒音频跑一步。流式模型默认 0.32 秒。"));
|
||||
generalForm->addRow(tr("更新粒度(秒)"), chunkSpin_);
|
||||
|
||||
root->addLayout(generalForm);
|
||||
|
||||
// ---- 流式:只影响 llama 后端的 Qwen3-ASR ----
|
||||
streamGroup_ = new QGroupBox(tr("流式(只影响 Qwen3-ASR)"), page);
|
||||
auto * streamForm = new QFormLayout(streamGroup_);
|
||||
|
||||
streamModeCombo_ = new QComboBox(streamGroup_);
|
||||
streamModeCombo_->addItem(tr("incremental — 增量复用,1~2 秒就出字(推荐)"),
|
||||
QStringLiteral("incremental"));
|
||||
streamModeCombo_->addItem(tr("append — 追加式,成本平坦但需要大 chunk"),
|
||||
QStringLiteral("append"));
|
||||
streamModeCombo_->addItem(tr("window — 每次重编码整个窗口(早期的对比实现)"),
|
||||
QStringLiteral("window"));
|
||||
{
|
||||
const int i = streamModeCombo_->findData(cfg.streamMode);
|
||||
if (i >= 0) streamModeCombo_->setCurrentIndex(i);
|
||||
}
|
||||
streamForm->addRow(tr("策略"), streamModeCombo_);
|
||||
|
||||
windowSpin_ = new QDoubleSpinBox(streamGroup_);
|
||||
windowSpin_->setRange(0.0, 120.0);
|
||||
windowSpin_->setDecimals(1);
|
||||
windowSpin_->setSpecialValueText(tr("不限"));
|
||||
windowSpin_->setValue(cfg.streamWindowSec);
|
||||
windowSpin_->setToolTip(tr("仅 window 模式使用:滑窗上限。"));
|
||||
streamForm->addRow(tr("滑窗上限(秒)"), windowSpin_);
|
||||
|
||||
segmentSpin_ = new QDoubleSpinBox(streamGroup_);
|
||||
segmentSpin_->setRange(0.0, 300.0);
|
||||
segmentSpin_->setDecimals(1);
|
||||
segmentSpin_->setSpecialValueText(tr("不限"));
|
||||
segmentSpin_->setValue(cfg.streamSegmentSec);
|
||||
segmentSpin_->setToolTip(tr("超过就提交并重置上下文。真实场景由静音检测分段,这是兜底上界。"));
|
||||
streamForm->addRow(tr("单段最长时长(秒)"), segmentSpin_);
|
||||
|
||||
unfixedTokenSpin_ = new QSpinBox(streamGroup_);
|
||||
unfixedTokenSpin_->setRange(0, 64);
|
||||
unfixedTokenSpin_->setValue(cfg.unfixedTokens);
|
||||
unfixedTokenSpin_->setToolTip(tr("回滚丢弃最后 N 个 token —— 它们会显示成灰色的不稳定尾部。"));
|
||||
streamForm->addRow(tr("前缀回滚 token 数"), unfixedTokenSpin_);
|
||||
|
||||
unfixedChunkSpin_ = new QSpinBox(streamGroup_);
|
||||
unfixedChunkSpin_->setRange(0, 32);
|
||||
unfixedChunkSpin_->setValue(cfg.unfixedChunks);
|
||||
unfixedChunkSpin_->setToolTip(tr("前 N 个 chunk 不带前缀(冷启动),用于避免开头重复。"));
|
||||
streamForm->addRow(tr("冷启动 chunk 数"), unfixedChunkSpin_);
|
||||
|
||||
maxTokenSpin_ = new QSpinBox(streamGroup_);
|
||||
maxTokenSpin_->setRange(16, 4096);
|
||||
maxTokenSpin_->setValue(cfg.maxTokens);
|
||||
maxTokenSpin_->setToolTip(tr("单段最多生成的 token 数。"));
|
||||
streamForm->addRow(tr("单段最多生成 token"), maxTokenSpin_);
|
||||
|
||||
threadsSpin_ = new QSpinBox(streamGroup_);
|
||||
threadsSpin_->setRange(1, 32);
|
||||
threadsSpin_->setValue(cfg.threads);
|
||||
threadsSpin_->setToolTip(tr("只影响 Qwen3-ASR;流式模型固定单线程,因为这类模型多线程反而更慢。"));
|
||||
streamForm->addRow(tr("线程数"), threadsSpin_);
|
||||
|
||||
streamNote_ = new QLabel(streamGroup_);
|
||||
streamNote_->setWordWrap(true);
|
||||
streamForm->addRow(QString(), streamNote_);
|
||||
|
||||
root->addWidget(streamGroup_);
|
||||
|
||||
// ---- 调试 ----
|
||||
auto * debugForm = new QFormLayout;
|
||||
|
||||
verboseCheck_ = new QCheckBox(tr("输出详细日志(llama.cpp / mtmd)"), page);
|
||||
verboseCheck_->setChecked(cfg.verbose);
|
||||
debugForm->addRow(QString(), verboseCheck_);
|
||||
|
||||
modelDirEdit_ = new QLineEdit(page);
|
||||
modelDirEdit_->setText(cfg.modelDir);
|
||||
modelDirEdit_->setPlaceholderText(ModelStore::root());
|
||||
modelDirEdit_->setToolTip(tr("留空 = 默认目录(占位符所示)。一般不需要改。"));
|
||||
debugForm->addRow(tr("模型目录"), modelDirEdit_);
|
||||
|
||||
root->addLayout(debugForm);
|
||||
root->addStretch(1);
|
||||
|
||||
updateStreamGroupEnabled();
|
||||
return page;
|
||||
}
|
||||
|
||||
// 「识别语言」的候选项按**所选模型**支持的语言来填:
|
||||
// 中文模型只给中文,Nemotron 给它的 16 种语言,Qwen3-ASR 给 52 语言里的常用项。
|
||||
// 这样既不会出现「选了模型不支持的语言」,也不会像以前那样只有中/英/日三项。
|
||||
void SettingsDialog::rebuildLanguageCombo()
|
||||
{
|
||||
if (!languageCombo_) return;
|
||||
const QString wanted = (languageCombo_->currentIndex() >= 0)
|
||||
? languageCombo_->currentData().toString()
|
||||
: AppSettings::instance().language;
|
||||
|
||||
QStringList langs;
|
||||
const QString id = (activeCombo_ && activeCombo_->currentIndex() >= 0)
|
||||
? activeCombo_->currentData().toString()
|
||||
: QString();
|
||||
if (const ModelInfo * m = id.isEmpty() ? nullptr : ModelStore::find(id)) {
|
||||
langs = m->languages;
|
||||
}
|
||||
if (langs.isEmpty()) langs = { QStringLiteral("zh"), QStringLiteral("en"), QStringLiteral("ja") };
|
||||
|
||||
languageCombo_->blockSignals(true);
|
||||
languageCombo_->clear();
|
||||
languageCombo_->addItem(tr("自动检测"), QString());
|
||||
for (const QString & code : langs) {
|
||||
if (code == QLatin1String("auto")) continue; // 第一项就是「自动」
|
||||
languageCombo_->addItem(
|
||||
QString::fromStdString(languageDisplayNameFromCode(code.toStdString())), code);
|
||||
}
|
||||
const int idx = languageCombo_->findData(wanted);
|
||||
languageCombo_->setCurrentIndex(idx >= 0 ? idx : 0);
|
||||
languageCombo_->blockSignals(false);
|
||||
}
|
||||
|
||||
// 流式那一组参数只对 llama 后端(Qwen3-ASR)有意义;
|
||||
// 选了流式 ONNX 模型时置灰,免得改了没效果。
|
||||
void SettingsDialog::updateStreamGroupEnabled()
|
||||
{
|
||||
if (!streamGroup_) return;
|
||||
const QString id = (activeCombo_ && activeCombo_->currentIndex() >= 0)
|
||||
? activeCombo_->currentData().toString()
|
||||
: QString();
|
||||
const ModelInfo * m = id.isEmpty() ? nullptr : ModelStore::find(id);
|
||||
const bool llamaBackend = m ? (m->backend == models::Backend::LlamaCpp) : true;
|
||||
|
||||
streamGroup_->setEnabled(llamaBackend);
|
||||
streamNote_->setText(llamaBackend
|
||||
? tr("这些参数对应命令行里的 --stream-mode / --stream-window / --stream-segment / "
|
||||
"--unfixed-tokens / --unfixed-chunks / --max-tokens / --threads。改动会重启识别后端。")
|
||||
: tr("当前模型是流式 ONNX(zipformer / X-ASR / Nemotron),这些参数不适用;"
|
||||
"它只用上面那个「更新粒度」。"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
void SettingsDialog::refreshModelTable()
|
||||
{
|
||||
const auto & reg = ModelStore::registry();
|
||||
table_->setRowCount((int) reg.size());
|
||||
for (int i = 0; i < (int) reg.size(); ++i) {
|
||||
const ModelInfo & m = reg[i];
|
||||
QStringList missing;
|
||||
const bool installed = ModelStore::isInstalled(m, &missing);
|
||||
|
||||
QStringList langs = m.languages;
|
||||
QString langText = langs.mid(0, 4).join(QStringLiteral(", "));
|
||||
if (langs.size() > 4) langText += QStringLiteral(" …");
|
||||
table_->setItem(i, 0, new QTableWidgetItem(m.name));
|
||||
table_->setItem(i, 1, new QTableWidgetItem(langText));
|
||||
table_->setItem(i, 2, new QTableWidgetItem(m.license));
|
||||
table_->setItem(i, 3, new QTableWidgetItem(installed ? tr("已安装") : tr("未安装")));
|
||||
table_->item(i, 0)->setData(Qt::UserRole, m.id);
|
||||
if (installed) {
|
||||
for (int c = 0; c < 4; ++c) table_->item(i, c)->setToolTip(m.note);
|
||||
} else {
|
||||
table_->item(i, 3)->setToolTip(tr("缺失: %1").arg(missing.join(QStringLiteral(", "))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SettingsDialog::refreshActiveCombo()
|
||||
{
|
||||
const QString current = AppSettings::instance().modelId;
|
||||
activeCombo_->blockSignals(true);
|
||||
activeCombo_->clear();
|
||||
for (const ModelInfo & m : ModelStore::registry()) {
|
||||
if (ModelStore::isInstalled(m)) {
|
||||
activeCombo_->addItem(m.name, m.id);
|
||||
}
|
||||
}
|
||||
const int idx = activeCombo_->findData(current);
|
||||
if (idx >= 0) activeCombo_->setCurrentIndex(idx);
|
||||
activeCombo_->blockSignals(false);
|
||||
if (idx >= 0) AppSettings::instance().modelId = activeCombo_->itemData(idx).toString();
|
||||
}
|
||||
|
||||
void SettingsDialog::onDownload()
|
||||
{
|
||||
const int row = table_->currentRow();
|
||||
if (row < 0) { statusLabel_->setText(tr("请先在上面选一个模型")); return; }
|
||||
const QString id = table_->item(row, 0)->data(Qt::UserRole).toString();
|
||||
const ModelInfo * m = ModelStore::find(id);
|
||||
if (!m) return;
|
||||
|
||||
downloader_->setMirrorBase(mirrorEdit_->text().trimmed());
|
||||
QNetworkProxy proxy;
|
||||
const int mode = proxyCombo_->currentData().toInt();
|
||||
if (mode == 1) {
|
||||
proxy = QNetworkProxy::applicationProxy();
|
||||
} else if (mode == 2 && !proxyHost_->text().isEmpty()) {
|
||||
proxy.setType(QNetworkProxy::HttpProxy);
|
||||
proxy.setHostName(proxyHost_->text().trimmed());
|
||||
proxy.setPort((quint16) proxyPort_->value());
|
||||
if (!proxyUser_->text().isEmpty()) {
|
||||
proxy.setUser(proxyUser_->text());
|
||||
proxy.setPassword(proxyPass_->text());
|
||||
}
|
||||
}
|
||||
downloader_->setProxy(proxy);
|
||||
|
||||
downloadBtn_->setEnabled(false);
|
||||
deleteBtn_->setEnabled(false);
|
||||
progress_->setVisible(true);
|
||||
progress_->setRange(0, 0);
|
||||
statusLabel_->setText(tr("开始下载…"));
|
||||
downloader_->start(*m);
|
||||
}
|
||||
|
||||
void SettingsDialog::onDelete()
|
||||
{
|
||||
const int row = table_->currentRow();
|
||||
if (row < 0) return;
|
||||
const QString id = table_->item(row, 0)->data(Qt::UserRole).toString();
|
||||
if (QMessageBox::question(this, tr("删除模型"),
|
||||
tr("确定要删除「%1」已下载的文件吗?").arg(id))
|
||||
!= QMessageBox::Yes) {
|
||||
return;
|
||||
}
|
||||
QDir(ModelStore::dirFor(id)).removeRecursively();
|
||||
if (AppSettings::instance().modelId == id) AppSettings::instance().modelId.clear();
|
||||
refreshModelTable();
|
||||
refreshActiveCombo();
|
||||
}
|
||||
|
||||
void SettingsDialog::onVerify()
|
||||
{
|
||||
const int row = table_->currentRow();
|
||||
if (row < 0) { statusLabel_->setText(tr("请先在上面选一个模型")); return; }
|
||||
const QString id = table_->item(row, 0)->data(Qt::UserRole).toString();
|
||||
const ModelInfo * m = ModelStore::find(id);
|
||||
if (!m) return;
|
||||
|
||||
statusLabel_->setText(tr("正在校验 %1 …").arg(m->name));
|
||||
progress_->setVisible(true);
|
||||
progress_->setRange(0, 100);
|
||||
QApplication::setOverrideCursor(Qt::WaitCursor);
|
||||
|
||||
QStringList bad;
|
||||
const bool ok = ModelStore::verify(*m, &bad, [this](int done, int total) {
|
||||
progress_->setValue(total > 0 ? done * 100 / total : 0);
|
||||
QApplication::processEvents();
|
||||
});
|
||||
|
||||
QApplication::restoreOverrideCursor();
|
||||
progress_->setVisible(false);
|
||||
if (ok) {
|
||||
statusLabel_->setText(tr("✅ %1 校验通过").arg(m->name));
|
||||
} else {
|
||||
statusLabel_->setText(tr("❌ 校验失败,损坏的文件: %1(可删除后重新下载)")
|
||||
.arg(bad.join(QStringLiteral(", "))));
|
||||
}
|
||||
}
|
||||
|
||||
void SettingsDialog::onOpenDir()
|
||||
{
|
||||
QDir().mkpath(ModelStore::root());
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(ModelStore::root()));
|
||||
}
|
||||
|
||||
bool SettingsDialog::ensureModelSelected()
|
||||
{
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
if (cfg.modelId.isEmpty() || !ModelStore::find(cfg.modelId) ||
|
||||
!ModelStore::isInstalled(*ModelStore::find(cfg.modelId))) {
|
||||
QMessageBox::warning(this, tr("还没有可用模型"),
|
||||
tr("请先在「模型」页下载一个模型,然后在「当前使用」里选中它。"));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void SettingsDialog::onAccept()
|
||||
{
|
||||
if (ensureModelSelected()) {
|
||||
applySettings();
|
||||
accept();
|
||||
}
|
||||
}
|
||||
|
||||
void SettingsDialog::onApplyClicked()
|
||||
{
|
||||
if (ensureModelSelected()) applySettings();
|
||||
}
|
||||
|
||||
void SettingsDialog::applySettings()
|
||||
{
|
||||
AppSettings & cfg = AppSettings::instance();
|
||||
cfg.mirrorBase = mirrorEdit_->text().trimmed();
|
||||
if (cfg.mirrorBase.isEmpty()) cfg.mirrorBase = QStringLiteral("https://hf-mirror.com");
|
||||
cfg.proxyMode = proxyCombo_->currentData().toInt();
|
||||
cfg.proxyHost = proxyHost_->text().trimmed();
|
||||
cfg.proxyPort = proxyPort_->value();
|
||||
cfg.proxyUser = proxyUser_->text();
|
||||
cfg.proxyPass = proxyPass_->text();
|
||||
cfg.language = languageCombo_->currentData().toString();
|
||||
if (captureCombo_->currentIndex() >= 0) {
|
||||
cfg.captureDevice = captureCombo_->currentData().toString();
|
||||
}
|
||||
|
||||
cfg.fontSize = fontSpin_->value();
|
||||
cfg.showUnstableTail = showTailCheck_->isChecked();
|
||||
cfg.collapsedLines = collapsedSpin_->value();
|
||||
cfg.expandedLines = expandedSpin_->value();
|
||||
cfg.opacityPercent = opacitySlider_->value();
|
||||
|
||||
cfg.chunkSec = chunkSpin_->value();
|
||||
cfg.threads = threadsSpin_->value();
|
||||
|
||||
cfg.streamMode = streamModeCombo_->currentData().toString();
|
||||
cfg.streamWindowSec = windowSpin_->value();
|
||||
cfg.streamSegmentSec = segmentSpin_->value();
|
||||
cfg.unfixedTokens = unfixedTokenSpin_->value();
|
||||
cfg.unfixedChunks = unfixedChunkSpin_->value();
|
||||
cfg.maxTokens = maxTokenSpin_->value();
|
||||
cfg.verbose = verboseCheck_->isChecked();
|
||||
cfg.modelDir = modelDirEdit_->text().trimmed();
|
||||
|
||||
if (activeCombo_->currentIndex() >= 0) {
|
||||
cfg.modelId = activeCombo_->currentData().toString();
|
||||
}
|
||||
cfg.save();
|
||||
Q_EMIT settingsApplied();
|
||||
}
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <QDialog>
|
||||
|
||||
class QComboBox;
|
||||
class QCheckBox;
|
||||
class QDoubleSpinBox;
|
||||
class QGroupBox;
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QProgressBar;
|
||||
class QPushButton;
|
||||
class QSlider;
|
||||
class QSpinBox;
|
||||
class QTableWidget;
|
||||
|
||||
namespace lc {
|
||||
|
||||
namespace models { class ModelDownloader; }
|
||||
|
||||
// 设置对话框:模型管理(下载/删除/选择)、显示、窗口、下载源与代理、高级。
|
||||
// GUI 用户完全靠它驱动,不再需要命令行参数。
|
||||
class SettingsDialog : public QDialog {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit SettingsDialog(bool firstRun, QWidget * parent = nullptr);
|
||||
~SettingsDialog() override;
|
||||
|
||||
Q_SIGNALS:
|
||||
// 设置已变更且用户点了确定
|
||||
void settingsApplied();
|
||||
|
||||
private:
|
||||
QWidget * buildModelPage();
|
||||
QWidget * buildDisplayPage();
|
||||
QWidget * buildAdvancedPage();
|
||||
|
||||
void refreshModelTable();
|
||||
void refreshActiveCombo();
|
||||
void rebuildLanguageCombo(); // 按所选模型支持的语言重建语言下拉
|
||||
void updateStreamGroupEnabled(); // 流式参数只在 llama 后端下可用
|
||||
void onDownload();
|
||||
void onVerify();
|
||||
void onDelete();
|
||||
void onOpenDir();
|
||||
void applySettings(); // 读取控件 → 保存 → 发 settingsApplied(不关闭对话框)
|
||||
void onAccept(); // 确定:applySettings + 关闭
|
||||
void onApplyClicked(); // 应用:只 applySettings
|
||||
bool ensureModelSelected();
|
||||
|
||||
QTableWidget * table_ = nullptr;
|
||||
QComboBox * activeCombo_ = nullptr;
|
||||
QComboBox * languageCombo_ = nullptr;
|
||||
QComboBox * captureCombo_ = nullptr;
|
||||
QPushButton * verifyBtn_ = nullptr;
|
||||
QPushButton * downloadBtn_ = nullptr;
|
||||
QPushButton * deleteBtn_ = nullptr;
|
||||
QProgressBar * progress_ = nullptr;
|
||||
QLabel * statusLabel_ = nullptr;
|
||||
|
||||
QLineEdit * mirrorEdit_ = nullptr;
|
||||
QComboBox * proxyCombo_ = nullptr;
|
||||
QLineEdit * proxyHost_ = nullptr;
|
||||
QSpinBox * proxyPort_ = nullptr;
|
||||
QLineEdit * proxyUser_ = nullptr;
|
||||
QLineEdit * proxyPass_ = nullptr;
|
||||
|
||||
QSpinBox * fontSpin_ = nullptr;
|
||||
QCheckBox * showTailCheck_ = nullptr;
|
||||
QSpinBox * collapsedSpin_ = nullptr;
|
||||
QSpinBox * expandedSpin_ = nullptr;
|
||||
QSlider * opacitySlider_ = nullptr;
|
||||
QLabel * opacityLabel_ = nullptr;
|
||||
|
||||
QDoubleSpinBox * chunkSpin_ = nullptr;
|
||||
QSpinBox * threadsSpin_ = nullptr;
|
||||
|
||||
// 高级:流式参数(只影响 llama 后端)
|
||||
QGroupBox * streamGroup_ = nullptr;
|
||||
QLabel * streamNote_ = nullptr;
|
||||
QComboBox * streamModeCombo_ = nullptr;
|
||||
QDoubleSpinBox * windowSpin_ = nullptr;
|
||||
QDoubleSpinBox * segmentSpin_ = nullptr;
|
||||
QSpinBox * unfixedTokenSpin_ = nullptr;
|
||||
QSpinBox * unfixedChunkSpin_ = nullptr;
|
||||
QSpinBox * maxTokenSpin_ = nullptr;
|
||||
|
||||
// 高级:调试
|
||||
QCheckBox * verboseCheck_ = nullptr;
|
||||
QLineEdit * modelDirEdit_ = nullptr;
|
||||
|
||||
models::ModelDownloader * downloader_ = nullptr;
|
||||
bool firstRun_ = false;
|
||||
};
|
||||
|
||||
} // namespace lc
|
||||
@@ -0,0 +1,15 @@
|
||||
# 单元测试:只依赖 core,不需要模型文件、不需要显示环境。
|
||||
# 需要真模型的集成测试不放在这里(会另外打 label)。
|
||||
find_package(Qt6 REQUIRED COMPONENTS Test)
|
||||
|
||||
function(lc_add_test name)
|
||||
add_executable(${name} ${name}.cpp)
|
||||
target_link_libraries(${name} PRIVATE livecaption_core Qt6::Test)
|
||||
target_include_directories(${name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_test(NAME ${name} COMMAND ${name})
|
||||
endfunction()
|
||||
|
||||
lc_add_test(tst_transcript)
|
||||
lc_add_test(tst_vad)
|
||||
lc_add_test(tst_streamingasr)
|
||||
lc_add_test(tst_livepipeline)
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "iasr.h"
|
||||
|
||||
// 可脚本化的假推理后端:让流式策略与实时管线可以脱离真模型测试。
|
||||
//
|
||||
// dropLastTokens 用"空格分词"模拟词表:丢掉最后 N 个词,并保留原有格式
|
||||
// (这点很重要 —— 续写开头那个空格是有意义的)。
|
||||
class FakeAsr : public lc::IAsr {
|
||||
public:
|
||||
// 每次 streamAppend 依次返回这里的文本;用完后返回空串
|
||||
std::vector<std::string> scripted;
|
||||
|
||||
// 记录(供断言用)
|
||||
std::vector<std::string> prefixesSeen;
|
||||
std::vector<std::string> turnsSeen;
|
||||
std::vector<size_t> samplesSeen;
|
||||
int resets = 0;
|
||||
|
||||
int sampleRate() const override { return 16000; }
|
||||
|
||||
lc::AsrResult transcribeWithPrefix(const float *, size_t,
|
||||
const std::string &) override
|
||||
{
|
||||
lc::AsrResult r;
|
||||
r.ok = true;
|
||||
if (call_ < scripted.size()) {
|
||||
r.raw = scripted[call_];
|
||||
r.transcript = lc::parseAsrOutput(r.raw);
|
||||
}
|
||||
++call_;
|
||||
return r;
|
||||
}
|
||||
|
||||
lc::AsrStreamStep streamAppend(const float *, size_t nSamples,
|
||||
const std::string & prefix, int) override
|
||||
{
|
||||
prefixesSeen.push_back(prefix);
|
||||
samplesSeen.push_back(nSamples);
|
||||
|
||||
lc::AsrStreamStep s;
|
||||
s.ok = true;
|
||||
if (call_ < scripted.size()) s.newText = scripted[call_];
|
||||
++call_;
|
||||
s.newTokens = 1;
|
||||
s.encodeSeconds = 0.001;
|
||||
s.inferSeconds = 0.001;
|
||||
return s;
|
||||
}
|
||||
|
||||
lc::AsrStreamStep streamAppendTurn(const float *, size_t nSamples, int) override
|
||||
{
|
||||
samplesSeen.push_back(nSamples);
|
||||
|
||||
lc::AsrStreamStep s;
|
||||
s.ok = true;
|
||||
if (call_ < scripted.size()) s.newText = scripted[call_];
|
||||
++call_;
|
||||
turnsSeen.push_back(s.newText);
|
||||
s.newTokens = 1;
|
||||
s.inferSeconds = 0.001;
|
||||
return s;
|
||||
}
|
||||
|
||||
void streamReset() override { ++resets; }
|
||||
|
||||
std::string dropLastTokens(const std::string & text, int dropLast) const override
|
||||
{
|
||||
if (dropLast <= 0 || text.empty()) return text;
|
||||
|
||||
const auto isSpace = [](char c) { return std::isspace((unsigned char) c) != 0; };
|
||||
|
||||
size_t pos = text.size();
|
||||
for (int i = 0; i < dropLast; ++i) {
|
||||
while (pos > 0 && isSpace(text[pos - 1])) --pos; // 跳过尾部空白
|
||||
while (pos > 0 && !isSpace(text[pos - 1])) --pos; // 跳过一个词
|
||||
if (pos == 0) return {};
|
||||
}
|
||||
while (pos > 0 && isSpace(text[pos - 1])) --pos;
|
||||
return text.substr(0, pos);
|
||||
}
|
||||
|
||||
private:
|
||||
size_t call_ = 0;
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "fakeasr.h"
|
||||
#include "livepipeline.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
std::vector<float> tone(size_t samples, float amplitude)
|
||||
{
|
||||
std::vector<float> v(samples);
|
||||
for (size_t i = 0; i < samples; ++i) {
|
||||
v[i] = amplitude * (float) std::sin(2.0 * kPi * 440.0 * (double) i / 16000.0);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
size_t totalSamples(const std::vector<size_t> & v)
|
||||
{
|
||||
size_t n = 0;
|
||||
for (size_t s : v) n += s;
|
||||
return n;
|
||||
}
|
||||
|
||||
lc::LivePipelineOptions options()
|
||||
{
|
||||
lc::LivePipelineOptions o;
|
||||
o.stream.chunkSec = 0.5; // 0.5s 一块,测试里能快些触发
|
||||
return o;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// 实时管线的回归测试(用 FakeAsr + 直接喂音频,不碰 PulseAudio)。
|
||||
class TstLivePipeline : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
// 静音不能送进模型。
|
||||
// 曾经把采集到的静音也喂了进去,模型对静音产生幻觉(英文语音前冒出一个"嗯。")。
|
||||
void silenceIsNotForwarded()
|
||||
{
|
||||
FakeAsr fake;
|
||||
lc::LivePipeline pipeline(fake, options());
|
||||
|
||||
const auto silence = tone(16000 * 3, 0.001f); // 3s 背景噪声
|
||||
pipeline.process(silence.data(), silence.size());
|
||||
|
||||
QCOMPARE(fake.samplesSeen.size(), size_t(0));
|
||||
}
|
||||
|
||||
// 不丢样本。
|
||||
// 曾经每次只处理 floor(可用/320) 帧并丢掉余数,每轮丢约 160 个样本,
|
||||
// 造成假静音和句子被截断。
|
||||
void noSamplesDroppedAcrossIrregularChunks()
|
||||
{
|
||||
FakeAsr fake;
|
||||
lc::LivePipeline pipeline(fake, options());
|
||||
|
||||
const auto speech = tone(16000 * 10, 0.1f); // 10s 语音
|
||||
const size_t sizes[] = {1000, 7, 3333, 999, 12345, 1};
|
||||
|
||||
size_t off = 0;
|
||||
int i = 0;
|
||||
while (off < speech.size()) {
|
||||
const size_t n = std::min(sizes[i++ % 6], speech.size() - off);
|
||||
pipeline.process(speech.data() + off, n);
|
||||
off += n;
|
||||
}
|
||||
|
||||
const size_t forwarded = totalSamples(fake.samplesSeen);
|
||||
// 允许剩下的不足一块留在引擎里(< 0.5s),其余都必须送到
|
||||
QVERIFY2(forwarded >= 16000 * 9,
|
||||
qPrintable(QString("只送到了 %1 个样本(共 %2)")
|
||||
.arg(forwarded).arg(speech.size())));
|
||||
}
|
||||
|
||||
// 静音够久要收束这一段(提交文本并重置上下文)
|
||||
void silenceEndsSegment()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"a b c d e f"};
|
||||
|
||||
lc::LivePipeline pipeline(fake, options());
|
||||
QString lastCommitted;
|
||||
pipeline.setCaptionCallback(
|
||||
[&lastCommitted](const std::string & committed, const std::string &,
|
||||
const std::string &) {
|
||||
lastCommitted = QString::fromStdString(committed);
|
||||
});
|
||||
|
||||
const auto speech = tone(16000 * 1, 0.1f);
|
||||
pipeline.process(speech.data(), speech.size());
|
||||
const int resetsAfterSpeech = fake.resets;
|
||||
|
||||
const auto silence = tone(16000 * 2, 0.001f);
|
||||
pipeline.process(silence.data(), silence.size());
|
||||
|
||||
QVERIFY2(fake.resets > resetsAfterSpeech, "静音后没有收束这一段");
|
||||
QVERIFY(!pipeline.inSegment());
|
||||
}
|
||||
|
||||
// 语音之后继续有语音:不应该被切断成很多段
|
||||
void continuousSpeechStaysInOneSegment()
|
||||
{
|
||||
FakeAsr fake;
|
||||
lc::LivePipeline pipeline(fake, options());
|
||||
const int resetsAfterConstruct = fake.resets; // 构造 StreamingAsr 时会 reset 一次
|
||||
|
||||
const auto speech = tone(16000 * 4, 0.1f);
|
||||
for (size_t off = 0; off < speech.size(); off += 4000) {
|
||||
const size_t n = std::min(size_t(4000), speech.size() - off);
|
||||
pipeline.process(speech.data() + off, n);
|
||||
}
|
||||
|
||||
QVERIFY(pipeline.inSegment());
|
||||
QCOMPARE(fake.resets, resetsAfterConstruct);
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TstLivePipeline)
|
||||
#include "tst_livepipeline.moc"
|
||||
@@ -0,0 +1,201 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "fakeasr.h"
|
||||
#include "streamingasr.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<float> chunk(size_t samples, float value = 0.1f)
|
||||
{
|
||||
return std::vector<float>(samples, value);
|
||||
}
|
||||
|
||||
QString q(const std::string & s) { return QString::fromStdString(s); }
|
||||
|
||||
} // namespace
|
||||
|
||||
// 流式策略的回归测试(用 FakeAsr,不加载真模型)。
|
||||
class TstStreamingAsr : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
private:
|
||||
static lc::StreamOptions baseOptions()
|
||||
{
|
||||
lc::StreamOptions o;
|
||||
o.chunkSec = 1.0; // 1s 一块,方便构造
|
||||
o.unfixedTokenNum = 1; // 回滚 1 个 token,断言更直观
|
||||
o.unfixedChunkNum = 0; // 默认就回喂前缀
|
||||
o.incremental = true;
|
||||
return o;
|
||||
}
|
||||
|
||||
private slots:
|
||||
// 冷启动阶段(前 unfixedChunkNum 块)不回喂前缀
|
||||
void coldStartHasNoPrefix()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"a b c d", "e f", "g h"};
|
||||
|
||||
lc::StreamOptions o = baseOptions();
|
||||
o.unfixedChunkNum = 2;
|
||||
|
||||
lc::StreamingAsr stream(fake, o);
|
||||
const auto cb = [](const lc::StreamingAsr::Step &) {};
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
|
||||
QCOMPARE(fake.prefixesSeen.size(), size_t(3));
|
||||
QCOMPARE(q(fake.prefixesSeen[0]), QString(""));
|
||||
QCOMPARE(q(fake.prefixesSeen[1]), QString(""));
|
||||
QVERIFY(!fake.prefixesSeen[2].empty());
|
||||
}
|
||||
|
||||
// 续写开头那个空格不能被吃掉。
|
||||
// 曾经用 trim 过的文本去拼接,导致 "potatoesand" 这种缺空格。
|
||||
void keepsJoiningSpace()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"language English<asr_text>He hoped there",
|
||||
" would be stew"};
|
||||
|
||||
lc::StreamingAsr stream(fake, baseOptions());
|
||||
|
||||
std::vector<lc::StreamingAsr::Step> steps;
|
||||
const auto cb = [&steps](const lc::StreamingAsr::Step & s) { steps.push_back(s); };
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
|
||||
QCOMPARE(steps.size(), size_t(2));
|
||||
QCOMPARE(q(steps[0].full), QString("He hoped there"));
|
||||
QVERIFY2(q(steps[1].full) == QString("He hoped would be stew"),
|
||||
qPrintable(QString("实际为 \"%1\"").arg(q(steps[1].full))));
|
||||
}
|
||||
|
||||
// 已提交文本 = 完整文本去掉最后 unfixedTokenNum 个 token;
|
||||
// 尾部单独作为不稳定部分给出。
|
||||
void committedDropsUnstableTail()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"language English<asr_text>He hoped there",
|
||||
" would be stew"};
|
||||
|
||||
lc::StreamingAsr stream(fake, baseOptions());
|
||||
std::vector<lc::StreamingAsr::Step> steps;
|
||||
const auto cb = [&steps](const lc::StreamingAsr::Step & s) { steps.push_back(s); };
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
|
||||
QCOMPARE(q(steps[1].committed), QString("He hoped would be"));
|
||||
QCOMPARE(q(steps[1].tail), QString(" stew"));
|
||||
// 已提交 + 尾部 = 完整文本
|
||||
QCOMPARE(q(steps[1].committed + steps[1].tail), q(steps[1].full));
|
||||
}
|
||||
|
||||
// 流结束时要全部提交,不能把尾部丢掉
|
||||
void flushCommitsEverything()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"language English<asr_text>one two three"};
|
||||
|
||||
lc::StreamOptions o = baseOptions();
|
||||
o.chunkSec = 100.0; // 特意设大:让音频留在 pending 里,由 flush 处理
|
||||
lc::StreamingAsr stream(fake, o);
|
||||
|
||||
std::vector<lc::StreamingAsr::Step> steps;
|
||||
const auto cb = [&steps](const lc::StreamingAsr::Step & s) { steps.push_back(s); };
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
QCOMPARE(steps.size(), size_t(0)); // 还没凑够一块
|
||||
|
||||
stream.flush(cb);
|
||||
QCOMPARE(steps.size(), size_t(1));
|
||||
QCOMPARE(q(steps[0].committed), QString("one two three"));
|
||||
QVERIFY(steps[0].tail.empty());
|
||||
}
|
||||
|
||||
// 多段:每段各自的 language 头都要剥掉,前面几段的正文不能丢。
|
||||
// 曾经用整段拼接后再解析,rfind 只保留最后一个头之后的内容,前面的正文全没了。
|
||||
void segmentsAccumulateWithoutLosingEarlierText()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"language Chinese<asr_text>ni hao shi jie",
|
||||
" language English<asr_text> hello there world"};
|
||||
|
||||
lc::StreamOptions o = baseOptions();
|
||||
o.chunkSec = 1.0;
|
||||
|
||||
lc::StreamingAsr stream(fake, o);
|
||||
const auto cb = [](const lc::StreamingAsr::Step &) {};
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb); // 第 1 段
|
||||
stream.flush(cb); // 收束第 1 段
|
||||
|
||||
stream.feed(c.data(), c.size(), cb); // 第 2 段
|
||||
stream.flush(cb);
|
||||
|
||||
const QString all = q(stream.committedText());
|
||||
QVERIFY2(all.contains("ni hao"), qPrintable(all));
|
||||
QVERIFY2(all.contains("hello there world"), qPrintable(all));
|
||||
}
|
||||
|
||||
// 追加式:每块音频作为新一轮追加,文本立即定稿,不回喂任何前缀
|
||||
void appendModeCommitsEachChunkImmediately()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"language English<asr_text>one two",
|
||||
" language English<asr_text> three four"};
|
||||
|
||||
lc::StreamOptions o = baseOptions();
|
||||
o.appendOnly = true;
|
||||
|
||||
lc::StreamingAsr stream(fake, o);
|
||||
std::vector<lc::StreamingAsr::Step> steps;
|
||||
const auto cb = [&steps](const lc::StreamingAsr::Step & s) { steps.push_back(s); };
|
||||
|
||||
const auto c = chunk(16000);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
|
||||
QCOMPARE(fake.turnsSeen.size(), size_t(2));
|
||||
QVERIFY2(fake.prefixesSeen.empty(), "追加式不应该回喂前缀");
|
||||
|
||||
QCOMPARE(steps.size(), size_t(2));
|
||||
QCOMPARE(q(steps[0].committed), QString("one two"));
|
||||
QVERIFY(steps[0].tail.empty()); // 追加式没有"不稳定尾部"
|
||||
QVERIFY(q(steps[1].committed).contains("three four"));
|
||||
}
|
||||
|
||||
// 同一次 feed 里跨多块也要正确切分
|
||||
void splitsMultipleChunksInOneFeed()
|
||||
{
|
||||
FakeAsr fake;
|
||||
fake.scripted = {"a b c", "d e f", "g h i"};
|
||||
|
||||
lc::StreamOptions o = baseOptions();
|
||||
lc::StreamingAsr stream(fake, o);
|
||||
int steps = 0;
|
||||
const auto cb = [&steps](const lc::StreamingAsr::Step &) { ++steps; };
|
||||
|
||||
const auto c = chunk(16000 * 3);
|
||||
stream.feed(c.data(), c.size(), cb);
|
||||
|
||||
QCOMPARE(steps, 3);
|
||||
QCOMPARE(fake.samplesSeen.size(), size_t(3));
|
||||
for (size_t n : fake.samplesSeen) QCOMPARE(n, size_t(16000));
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TstStreamingAsr)
|
||||
#include "tst_streamingasr.moc"
|
||||
@@ -0,0 +1,82 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include "transcript.h"
|
||||
|
||||
// 输出解析:Qwen3-ASR 的原始输出形如 "language English<asr_text>正文"
|
||||
class TstTranscript : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void splitsLanguageAndText()
|
||||
{
|
||||
const auto r = lc::parseAsrOutput("language English<asr_text>He hoped there would be stew.");
|
||||
QCOMPARE(QString::fromStdString(r.language), QString("English"));
|
||||
QCOMPARE(QString::fromStdString(r.text), QString("He hoped there would be stew."));
|
||||
}
|
||||
|
||||
void handlesChinese()
|
||||
{
|
||||
const auto r = lc::parseAsrOutput("language Chinese<asr_text>不排除购房者可以在互联网上下单。");
|
||||
QCOMPARE(QString::fromStdString(r.language), QString("Chinese"));
|
||||
QCOMPARE(QString::fromStdString(r.text), QString("不排除购房者可以在互联网上下单。"));
|
||||
}
|
||||
|
||||
void withoutMarkerKeepsWholeText()
|
||||
{
|
||||
const auto r = lc::parseAsrOutput(" just text ");
|
||||
QVERIFY(r.language.empty());
|
||||
QCOMPARE(QString::fromStdString(r.text), QString("just text"));
|
||||
}
|
||||
|
||||
void trimsSurroundingWhitespaceOfBody()
|
||||
{
|
||||
const auto r = lc::parseAsrOutput("language English<asr_text> hi there ");
|
||||
QCOMPARE(QString::fromStdString(r.text), QString("hi there"));
|
||||
}
|
||||
|
||||
void displayNameMapping()
|
||||
{
|
||||
QCOMPARE(QString::fromStdString(lc::languageDisplayName("English")), QString("英语"));
|
||||
QCOMPARE(QString::fromStdString(lc::languageDisplayName("Chinese")), QString("中文"));
|
||||
// 未收录的语言原样返回
|
||||
QCOMPARE(QString::fromStdString(lc::languageDisplayName("Klingon")), QString("Klingon"));
|
||||
QVERIFY(lc::languageDisplayName("").empty());
|
||||
}
|
||||
|
||||
// 设置里的语言提示是 ISO 码,界面要把它显示成中文名。
|
||||
// 覆盖注册表里出现过的所有语言码,避免加了模型却漏了显示名。
|
||||
void isoCodeDisplayName()
|
||||
{
|
||||
const struct { const char * code; const char * display; } kCases[] = {
|
||||
{ "zh", "中文" }, { "en", "英语" }, { "ja", "日语" },
|
||||
{ "ko", "韩语" }, { "fr", "法语" }, { "de", "德语" },
|
||||
{ "es", "西班牙语" },{ "ru", "俄语" }, { "ar", "阿拉伯语" },
|
||||
{ "hi", "印地语" }, { "vi", "越南语" }, { "it", "意大利语" },
|
||||
{ "pt", "葡萄牙语" },{ "nl", "荷兰语" }, { "tr", "土耳其语" },
|
||||
{ "uk", "乌克兰语" },{ "auto", "自动检测" },
|
||||
};
|
||||
for (const auto & c : kCases) {
|
||||
QCOMPARE(QString::fromStdString(lc::languageDisplayNameFromCode(c.code)),
|
||||
QString::fromUtf8(c.display));
|
||||
}
|
||||
// 未知码原样返回;空串返回空
|
||||
QCOMPARE(QString::fromStdString(lc::languageDisplayNameFromCode("xx")), QString("xx"));
|
||||
QVERIFY(lc::languageDisplayNameFromCode("").empty());
|
||||
}
|
||||
|
||||
// 注册表里每个模型声明的语言都必须能显示成中文名,
|
||||
// 否则设置里的「识别语言」下拉会出现英文码。
|
||||
void registryLanguagesAllHaveDisplayNames()
|
||||
{
|
||||
for (const char * code : { "zh", "en", "ja", "ko", "fr", "de", "es", "ru", "ar",
|
||||
"hi", "vi", "it", "pt", "nl", "tr", "uk" }) {
|
||||
const QString display =
|
||||
QString::fromStdString(lc::languageDisplayNameFromCode(code));
|
||||
QVERIFY2(display != QString::fromLatin1(code),
|
||||
qPrintable(QStringLiteral("语言码没有显示名: %1").arg(code)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TstTranscript)
|
||||
#include "tst_transcript.moc"
|
||||
@@ -0,0 +1,83 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "vad.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t kFrame = 320; // 20ms @16k
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
// 生成 amplitude 幅值的 440Hz 正弦,用来模拟"有内容"的音频
|
||||
std::vector<float> tone(size_t samples, float amplitude)
|
||||
{
|
||||
std::vector<float> v(samples);
|
||||
for (size_t i = 0; i < samples; ++i) {
|
||||
v[i] = amplitude * (float) std::sin(2.0 * kPi * 440.0 * (double) i / 16000.0);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
int countSpeech(lc::Vad & vad, const std::vector<float> & audio)
|
||||
{
|
||||
int speech = 0;
|
||||
for (size_t off = 0; off + kFrame <= audio.size(); off += kFrame) {
|
||||
if (vad.feed(audio.data() + off, kFrame)) ++speech;
|
||||
}
|
||||
return speech;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// VAD 的回归测试。
|
||||
//
|
||||
// 关键教训:噪声底必须用"最小值跟踪"。曾经用均值跟踪,遇到本来就很轻的音频
|
||||
// (峰值 RMS 只有 0.03 量级的录音)会把阈值抬到语音电平之上,把绝大部分话音
|
||||
// 判成静音 —— 实时字幕于是每句都被切断。
|
||||
class TstVad : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void backgroundStaysSilent()
|
||||
{
|
||||
lc::Vad vad;
|
||||
const auto bg = tone(kFrame * 200, 0.001f); // rms ≈ 0.0007
|
||||
QCOMPARE(countSpeech(vad, bg), 0);
|
||||
}
|
||||
|
||||
// 轻语音必须被判成语音:这里语音 rms ≈ 0.0028,
|
||||
// 旧的"均值跟踪 + 0.004 绝对下限"实现会全部漏掉。
|
||||
void quietSpeechIsDetected()
|
||||
{
|
||||
lc::Vad vad;
|
||||
const auto bg = tone(kFrame * 40, 0.001f); // rms ≈ 0.0007
|
||||
countSpeech(vad, bg);
|
||||
|
||||
const auto sp = tone(kFrame * 100, 0.004f); // rms ≈ 0.0028
|
||||
const int speech = countSpeech(vad, sp);
|
||||
QVERIFY2(speech >= 95,
|
||||
qPrintable(QString("轻语音只被识别出 %1/100 帧").arg(speech)));
|
||||
}
|
||||
|
||||
void loudSpeechIsDetected()
|
||||
{
|
||||
lc::Vad vad;
|
||||
const auto sp = tone(kFrame * 50, 0.2f);
|
||||
QVERIFY(countSpeech(vad, sp) >= 48);
|
||||
}
|
||||
|
||||
void floorFollowsQuietInput()
|
||||
{
|
||||
lc::Vad vad;
|
||||
const auto bg = tone(kFrame * 200, 0.001f);
|
||||
countSpeech(vad, bg);
|
||||
// 噪声底应该已经下探到背景噪声量级,而不是停在初值
|
||||
QVERIFY2(vad.noiseFloor() < 0.002f,
|
||||
qPrintable(QString("噪声底仍为 %1").arg(vad.noiseFloor())));
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TstVad)
|
||||
#include "tst_vad.moc"
|
||||
Reference in new issue
Block a user