Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(android): Android tells the other side's voices apart and names them, with the Mac's voiceprint model

wquguru31675397078a
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
index ffe8b2e..fd78cfd 100644
--- a/.github/workflows/android.yml
+++ b/.github/workflows/android.yml
@@ -7,9 +7,9 @@ name: android
on:
push:
branches: [main]
- paths: ["android/**", "Resources/**/Localizable.strings", ".github/workflows/android.yml"]
+ paths: ["android/**", "Resources/**/Localizable.strings", "linux/native/voiceprint.c", "linux/models/voiceprint.bin", ".github/workflows/android.yml"]
pull_request:
- paths: ["android/**", "Resources/**/Localizable.strings", ".github/workflows/android.yml"]
+ paths: ["android/**", "Resources/**/Localizable.strings", "linux/native/voiceprint.c", "linux/models/voiceprint.bin", ".github/workflows/android.yml"]
workflow_dispatch:
inputs:
sign:
@@ -38,6 +38,9 @@ jobs:
JAVA_OPTS="-Dcicada.resources=$PWD/../Resources -Dcicada.androidStrings=$PWD/app/src/main/strings" cli/build/install/cicada-cli/bin/cicada-cli test
- name: Translations
run: python3 scripts/strings.py
+ # 说话人识别's voiceprint library: the NDK app/build.gradle.kts pins (sdkmanager checks it).
+ - name: NDK
+ run: "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "ndk;29.0.14206865" > /dev/null
- name: Build
run: gradle --console=plain -q :app:assembleDebug
- uses: actions/upload-artifact@v4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8c56a4a..e24a6b5 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -199,6 +199,9 @@ jobs:
gradle --console=plain -q :cli:installDist
JAVA_OPTS="-Dcicada.resources=$PWD/../Resources -Dcicada.androidStrings=$PWD/app/src/main/strings" cli/build/install/cicada-cli/bin/cicada-cli test
python3 scripts/strings.py
+ # 说话人识别's voiceprint library: the NDK app/build.gradle.kts pins (sdkmanager checks it).
+ - name: NDK
+ run: "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "ndk;29.0.14206865" > /dev/null
- name: Build and sign
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
diff --git a/android/AGENTS.md b/android/AGENTS.md
index e5e1a83..a302880 100644
--- a/android/AGENTS.md
+++ b/android/AGENTS.md
@@ -3,6 +3,7 @@
The Android port: listening, plus 我说 in 面对面 (hold, speak, the phone reads the translation aloud; no virtual mic, so never into another app's call). The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/android-plan.md`.
- Kotlin and the Android framework only: no AndroidX, Compose or other libraries; UI in code, no XML layouts. `core` is plain JVM and must build and test on the Mac.
+- 说话人识别 runs Linux's `native/voiceprint.c` (the Mac's model) through the NDK (`app/src/main/jni`): never copy or fork that C, and keep thresholds, labels and Ling's name prompt the Mac's.
- Keys: `AIKey` in `core/.../Ling.kt`, one Keystore-sealed file per AI service in the app's private folder (`ling-api-key`, `ai-key-<service>`, as on the Mac), kept out of backups. The services and their recommended models are `core/.../Providers.kt`; every AI call goes through `LingClient`, which reads the service from settings on each call.
- 我说 speaks only `ListenEngine.speakable` text (a translation, never my words), in the service's voice when it has one (not Ling's), else the phone's, and mutes the segmenter while the phone speaks.
- The overlay is `FLAG_NOT_FOCUSABLE` and `FLAG_SECURE` unless 共享屏幕时让对方看到 is on.
diff --git a/android/README.md b/android/README.md
index 7f3f166..0ec4f55 100644
--- a/android/README.md
+++ b/android/README.md
@@ -7,7 +7,8 @@ Cicada 的 Android 版:把手机里播放的声音(或面对面时麦克风
- 悬浮窗:纪要或字幕条,`FLAG_NOT_FOCUSABLE` 不抢输入,`FLAG_SECURE` 默认不出现在截图和录屏里;打开“共享屏幕时让对方看到”后显示“对方可见”。
- 纪要、记录格式(逐字节和 Mac 一致)、提示词、文案都和 Mac 版一致;英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Android 独有的在 `app/src/main/strings/`。
- 检查更新:每天在后台查一次 GitHub Releases,有新版本时在首页、设置和通知里提示,点“更新”用浏览器下载 APK,由系统安装器覆盖安装(签名一致才行),不需要安装权限。
-- 只用 Kotlin 标准库和 Android 框架,不用 AndroidX、Compose 或其他库。
+- 说话人识别(默认打开,和 Mac 一样):每句话的声音在手机上算一个声纹,按 Mac 的阈值分组,标出说话人 1、2…,Ling 从对话里认出名字。声纹模型和 Mac 是同一个(WeSpeaker ResNet34-LM,VoxCeleb,CC BY 4.0);推理用 Linux 版自己写的 C(`linux/native/voiceprint.c`),由 NDK 编成 `libcicada-voice.so`(arm64-v8a、armeabi-v7a、x86_64),权重是 `linux/models/voiceprint.bin`(13 MB),构建时拷进 assets。库加载不了时只显示别处分好的说话人,听照常。
+- 只用 Kotlin 标准库和 Android 框架,不用 AndroidX、Compose 或其他库;唯一的原生库是上面自己写的 C。
## 目录
@@ -21,7 +22,7 @@ Cicada 的 Android 版:把手机里播放的声音(或面对面时麦克风
## 命令(在 Mac 上)
```bash
-scripts/install-sdk.sh # 一次:JDK、Gradle、Android SDK、模拟器装到 ~/.cicada-android,不用 sudo;版本固定,下载都校验哈希;--old 再装一个 Android 10 模拟器
+scripts/install-sdk.sh # 一次:JDK、Gradle、Android SDK、NDK、模拟器装到 ~/.cicada-android,不用 sudo;版本固定,下载都校验哈希;--old 再装一个 Android 10 模拟器
scripts/test.sh # 单元测试
scripts/build.sh # 开发版 build/Cicada-dev.apk(com.wquguru.cicada.dev);RELEASE=1 出签名的 build/Cicada-<版本>-Android.apk
scripts/keystore.sh # 一次:生成发布签名密钥(~/.cicada-android/release.jks,密码在钥匙串);--github 顺便存进 Actions secrets。文件和密码都要备份,丢了就没法给已装的人升级
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index 01b3de7..3ab13e0 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -1,4 +1,5 @@
-// The Android app. AGP 9 compiles Kotlin itself; no AndroidX, no libraries beyond :core.
+// The Android app. AGP 9 compiles Kotlin itself; no AndroidX, no libraries beyond :core. Its one
+// native library is our own C (src/main/jni), built with the NDK.
plugins { id("com.android.application") }
// One version for every platform: VERSION at the repo root. versionCode must only grow: 1.2.3 → 10203.
@@ -13,13 +14,21 @@ val releaseKeystore = System.getenv("CICADA_KEYSTORE")?.let { file(it) }?.takeIf
android {
namespace = "com.wquguru.cicada"
compileSdk = 36
+ // 说话人识别's voiceprint library (src/main/jni): scripts/install-sdk.sh and CI install this NDK.
+ ndkVersion = "29.0.14206865"
defaultConfig {
applicationId = "com.wquguru.cicada"
minSdk = 29
targetSdk = 36
versionCode = appVersionCode
versionName = appVersion
+ // Every phone (64- and 32-bit ARM) and the arm64 or x86_64 emulator: an APK with native code
+ // doesn't install on an ABI it leaves out.
+ ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
}
+ externalNativeBuild { ndkBuild { path = file("src/main/jni/Android.mk") } }
+ // The voiceprint weights stay uncompressed: NativeVoiceprints sizes the asset to know its copy is whole.
+ androidResources { noCompress += "bin" }
signingConfigs {
if (releaseKeystore != null) create("release") {
storeFile = releaseKeystore
@@ -40,7 +49,12 @@ android {
}
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
buildFeatures { buildConfig = true }
- sourceSets { getByName("main") { assets.directories.add(layout.buildDirectory.dir("generated/strings").get().asFile.path) } }
+ sourceSets {
+ getByName("main") {
+ assets.directories.add(layout.buildDirectory.dir("generated/strings").get().asFile.path)
+ assets.directories.add(layout.buildDirectory.dir("generated/voiceprint").get().asFile.path)
+ }
+ }
}
kotlin { jvmToolchain(21) }
@@ -55,4 +69,10 @@ val copyStrings by tasks.registering(Sync::class) {
from(file("src/main/strings/$lang.lproj")) { include("Android.strings"); into("$lang.lproj") }
}
}
-tasks.named("preBuild") { dependsOn(copyStrings) }
+// 说话人识别's weights: the Linux app's linux/models/voiceprint.bin (the Mac's model, converted by
+// linux/scripts/convert-voiceprint.py), not a second copy in the repo.
+val copyVoiceprint by tasks.registering(Sync::class) {
+ from(rootProject.file("../linux/models")) { include("voiceprint.bin") }
+ into(layout.buildDirectory.dir("generated/voiceprint"))
+}
+tasks.named("preBuild") { dependsOn(copyStrings, copyVoiceprint) }
diff --git a/android/app/src/main/jni/Android.mk b/android/app/src/main/jni/Android.mk
new file mode 100644
index 0000000..6b42131
--- /dev/null
+++ b/android/app/src/main/jni/Android.mk
@@ -0,0 +1,12 @@
+# libcicada-voice.so: 说话人识别's voiceprint model. The C is the Linux app's (linux/native/voiceprint.c),
+# not a copy, so both stay the Mac's; voiceprint_jni.c only hands calls over. Built by ndk-build
+# from app/build.gradle.kts. 16 KB pages (Android 15+ phones) need the alignment flag.
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := cicada-voice
+LOCAL_SRC_FILES := voiceprint_jni.c ../../../../../linux/native/voiceprint.c
+LOCAL_CFLAGS := -O3 -Wall -Wextra
+LOCAL_LDLIBS := -lm
+LOCAL_LDFLAGS := -Wl,-z,max-page-size=16384
+include $(BUILD_SHARED_LIBRARY)
diff --git a/android/app/src/main/jni/Application.mk b/android/app/src/main/jni/Application.mk
new file mode 100644
index 0000000..a65c2e8
--- /dev/null
+++ b/android/app/src/main/jni/Application.mk
@@ -0,0 +1,2 @@
+APP_PLATFORM := android-29
+APP_OPTIM := release
diff --git a/android/app/src/main/jni/voiceprint_jni.c b/android/app/src/main/jni/voiceprint_jni.c
new file mode 100644
index 0000000..daaf6ac
--- /dev/null
+++ b/android/app/src/main/jni/voiceprint_jni.c
@@ -0,0 +1,35 @@
+/* NativeVoiceprints (Voiceprints.kt) → linux/native/voiceprint.c, the voiceprint model the Linux app
+ * runs; the same C, so an Android voiceprint is the Mac's. Only the calls, no logic of its own. */
+#include <jni.h>
+#include <stdint.h>
+
+void *cvp_load(const char *path);
+int cvp_embed_s16(void *model, const int16_t *samples, int n, float *out, int threads);
+int cvp_dims(void *model);
+
+JNIEXPORT jlong JNICALL
+Java_com_wquguru_cicada_NativeVoiceprints_nativeLoad(JNIEnv *env, jobject self, jstring path) {
+ (void)self;
+ const char *p = (*env)->GetStringUTFChars(env, path, NULL);
+ if (!p) return 0;
+ void *m = cvp_load(p);
+ (*env)->ReleaseStringUTFChars(env, path, p);
+ /* Voiceprints.kt reads 256 numbers: a model of another size is no model. */
+ return m && cvp_dims(m) == 256 ? (jlong)(intptr_t)m : 0;
+}
+
+/* 0 with a unit-length voiceprint in `out`, -1 when too short or it failed. Threads 0: one per
+ * core, at most four (voiceprint.c). */
+JNIEXPORT jint JNICALL
+Java_com_wquguru_cicada_NativeVoiceprints_nativeEmbed(JNIEnv *env, jobject self, jlong model, jshortArray samples,
+ jint n, jfloatArray out) {
+ (void)self;
+ if (!model || n > (*env)->GetArrayLength(env, samples)) return -1;
+ jshort *s = (*env)->GetShortArrayElements(env, samples, NULL);
+ if (!s) return -1;
+ float v[256];
+ int r = cvp_embed_s16((void *)(intptr_t)model, (const int16_t *)s, n, v, 0);
+ (*env)->ReleaseShortArrayElements(env, samples, s, JNI_ABORT);
+ if (r == 0) (*env)->SetFloatArrayRegion(env, out, 0, 256, v);
+ return r;
+}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index fb4125f..db45daf 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -21,6 +21,8 @@ import cicada.PcmAudioSource
import cicada.Providers
import cicada.SessionStore
import cicada.SpeakerLabels
+import cicada.SpeakerNamer
+import cicada.SpeakerTagger
import cicada.Strings
import cicada.Translator
import cicada.Wav
@@ -39,6 +41,7 @@ class CicadaApp : Application() {
lateinit var notes: NotesEngine
lateinit var translator: Translator
lateinit var listen: ListenEngine
+ lateinit var namer: SpeakerNamer
lateinit var overlay: Overlay
lateinit var voice: Voice
lateinit var updates: AppUpdates
@@ -91,6 +94,10 @@ class CicadaApp : Application() {
translator = Translator(ling)
translator.googleOff = settings.customOnly
listen = ListenEngine(ling, translator, store, notes, settings)
+ // 说话人识别: voiceprints on the phone, names from Ling once two voices are on show.
+ listen.speakers = SpeakerTagger(NativeVoiceprints.create(this))
+ namer = SpeakerNamer(ling, store)
+ listen.onVoice = { namer.guess(it) }
listen.encoder = { pcm ->
val t = System.currentTimeMillis()
AacEncoder.encode(pcm)?.also { Log.d("listen: ${pcm.size * 2 / 1024} KB PCM → ${it.bytes.size / 1024} KB ${it.type} in ${System.currentTimeMillis() - t} ms") }
@@ -337,6 +344,8 @@ class CicadaApp : Application() {
val imported = importing; importing = null
background.execute {
listen.stop(endedAt)
+ // The whole meeting read once more for names.
+ recId?.let { namer.guess(it, force = true) }
if (imported != null && recId != null) store.update(recId) { it.importing = null }
rec?.finish { ok -> if (ok && recId != null && store.get(recId) != null) store.update(recId) { it.hasAudio = true } }
main.post {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
index 1d5d2ff..045c8d7 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
@@ -65,12 +65,14 @@ class SettingsActivity : Activity() {
s.uiLanguage = it; app.saveSettings(); app.loadStrings(); shown = null; recreate()
})))
- // 听对方: the Mac's listening switches. Android doesn't tell voices apart itself yet (no
- // voiceprint runtime in the framework), so 说话人识别 numbers the voices of records made
- // on the Mac or Windows; the helper says so.
+ // 听对方: the Mac's listening switches. 说话人识别 tells voices apart on the phone
+ // (NativeVoiceprints); should the library not load, it still numbers the voices of
+ // records made elsewhere, and the helper says so.
page.addView(ui.sectionLabel(L("听对方")))
+ val voicesHere = app.listen.speakers?.available == true
page.addView(ui.group(listOf(
- ui.switchRow(L("说话人识别"), L("显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人"), s.speakerVoices) { s.speakerVoices = it; app.saveSettings() },
+ ui.switchRow(L("说话人识别"), if (voicesHere) L("按声音标出说话人 1、2…,只在这台手机上处理") else L("显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人"),
+ s.speakerVoices) { s.speakerVoices = it; app.saveSettings() },
ui.switchRow(L("保存会议录音"), L("只存在这台手机上,会议记录里能回放原声"), s.recordAudio) { s.recordAudio = it; app.saveSettings() })))
page.addView(ui.sectionLabel(L("我说 · 面对面")))
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt
new file mode 100644
index 0000000..9f283cb
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt
@@ -0,0 +1,59 @@
+package com.wquguru.cicada
+
+import android.content.Context
+import cicada.Log
+import cicada.Voiceprinter
+import java.io.File
+
+/// 说话人识别's voiceprints on the phone: the Mac's model (WeSpeaker ResNet34-LM, VoxCeleb, CC BY
+/// 4.0) run by linux/native/voiceprint.c, built with the NDK into libcicada-voice.so (src/main/jni).
+/// The weights are linux/models/voiceprint.bin, an asset copied out once (the C reads a file).
+/// Should the library not load, `create` gives null and listening carries on unlabelled.
+class NativeVoiceprints private constructor(private val context: Context) : Voiceprinter {
+ private var model = 0L
+ private var tried = false
+
+ override fun embed(samples: ShortArray): FloatArray? {
+ val m = synchronized(this) {
+ if (!tried) { tried = true; model = load() }
+ model
+ }
+ if (m == 0L) return null
+ val out = FloatArray(DIMS)
+ // One at a time: each already uses up to four cores.
+ return synchronized(this) { if (nativeEmbed(m, samples, samples.size, out) == 0) out else null }
+ }
+
+ private fun load(): Long {
+ val t = System.currentTimeMillis()
+ return try {
+ val file = File(context.noBackupFilesDir, "voiceprint.bin")
+ val size = context.assets.openFd(ASSET).use { it.length }
+ if (file.length() != size) {
+ val tmp = File(file.path + ".tmp")
+ context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
+ if (!tmp.renameTo(file)) { tmp.delete(); return 0 }
+ }
+ nativeLoad(file.path).also { Log.d("speakers: voiceprint model ${if (it != 0L) "loaded" else "failed to load"} in ${System.currentTimeMillis() - t} ms") }
+ } catch (e: Exception) {
+ Log.d("speakers: voiceprint model failed ${e.javaClass.simpleName}")
+ 0
+ }
+ }
+
+ private external fun nativeLoad(path: String): Long
+ private external fun nativeEmbed(model: Long, samples: ShortArray, n: Int, out: FloatArray): Int
+
+ companion object {
+ const val DIMS = 256
+ private const val ASSET = "voiceprint.bin"
+
+ fun create(context: Context): NativeVoiceprints? = try {
+ System.loadLibrary("cicada-voice")
+ NativeVoiceprints(context.applicationContext)
+ } catch (e: Throwable) {
+ Log.d("speakers: no voiceprint library (${e.javaClass.simpleName})")
+ null
+ }
+ }
+}
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index e98fe44..7601eb7 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -160,6 +160,7 @@
"只改这场会议,前面的字幕和纪要一起改" = "This meeting only. Earlier subtitles and notes change too.";
"播放原声" = "Play recording";
"配回原视频用" = "To put back on the video";
+"按声音标出说话人 1、2…,只在这台手机上处理" = "Labels lines Speaker 1, 2… by voice, on this phone only";
"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Shows speakers told apart on Mac and Windows. This phone can't tell voices apart yet.";
"只存在这台手机上,会议记录里能回放原声" = "Kept on this phone only. Play it back in the record.";
"我说 · 面对面" = "Me · In person";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index b74b043..dc717e3 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -160,6 +160,7 @@
"只改这场会议,前面的字幕和纪要一起改" = "この会議だけ。これまでの字幕とメモも変わります";
"播放原声" = "録音を再生";
"配回原视频用" = "元の動画に付けるとき";
+"按声音标出说话人 1、2…,只在这台手机上处理" = "声で話者 1、2… を区別します。処理はこのスマホ内だけ";
"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Mac と Windows で分けた話者を表示します。このスマホはまだ声で話者を分けられません";
"只存在这台手机上,会议记录里能回放原声" = "このスマホにだけ保存。会議記録で再生できます";
"我说 · 面对面" = "自分 · 対面";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index dd772f0..214a6e9 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -160,6 +160,7 @@
"只改这场会议,前面的字幕和纪要一起改" = "이 회의에만 적용돼요. 앞의 자막과 노트도 함께 바뀌어요";
"播放原声" = "녹음 재생";
"配回原视频用" = "원래 영상에 붙일 때";
+"按声音标出说话人 1、2…,只在这台手机上处理" = "목소리로 화자 1, 2…를 구분해요. 이 휴대전화에서만 처리해요";
"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Mac과 Windows에서 구분한 화자를 보여 줘요. 이 휴대전화는 아직 목소리로 구분하지 못해요";
"只存在这台手机上,会议记录里能回放原声" = "이 휴대전화에만 저장돼요. 회의 기록에서 다시 들을 수 있어요";
"我说 · 面对面" = "나 · 대면";
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 01cf421..63d944f 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -83,6 +83,12 @@ object Tests {
"lingGateSpacesStartsAndServesPriorityFirst" to ::lingGate,
"listenEngineEndToEndWithAFakeMing" to ::listenEndToEnd,
"listenSaysServerErrorsInARowAndClearsThem" to ::listenServerErrors,
+ "clustererMatchesTheMac" to ::clustererMatchesTheMac,
+ "numbersWaitForTwoVoicesWithFiveLines" to ::numbersWaitForTwoVoices,
+ "lingNamesNeedEvidenceNearTheVoice" to ::lingNamesNeedEvidence,
+ "notesPromptNamesTheVoices" to ::notesPromptNamesTheVoices,
+ "aHalfSentenceJoinsOnlyTheSameVoice" to ::aHalfSentenceJoinsOnlyTheSameVoice,
+ "slowVoiceprintsNeverHoldSubtitlesBack" to ::slowVoiceprintsNeverHoldSubtitlesBack,
) + ProviderTests.tests + AICheckTests.tests
var passed = 0; var failed = 0
for ((name, test) in tests) {
@@ -1086,6 +1092,149 @@ object Tests {
check(PressSpeech.filler("嗯嗯。") && PressSpeech.filler("Um, uh...") && !PressSpeech.filler("嗯,好的。") && !PressSpeech.filler("OK."), "fillers")
}
+ // MARK: 说话人识别 (linux/tests/test_core.py › Speakers)
+
+ private fun unit(seed: Long, dims: Int = 256): FloatArray {
+ val r = java.util.Random(seed)
+ val v = FloatArray(dims) { r.nextGaussian().toFloat() }
+ val n = kotlin.math.sqrt(v.sumOf { (it * it).toDouble() }).toFloat()
+ return FloatArray(dims) { v[it] / n }
+ }
+
+ private fun near(v: FloatArray, seed: Long, mix: Float = 0.3f): FloatArray {
+ val w = unit(seed)
+ val out = FloatArray(v.size) { v[it] + mix * w[it] }
+ val n = kotlin.math.sqrt(out.sumOf { (it * it).toDouble() }).toFloat()
+ return FloatArray(out.size) { out[it] / n }
+ }
+
+ private fun them(i: Int, voice: Int?, text: String = "we should ship this on Friday", t: Double = i.toDouble()) =
+ TranscriptLine(id = "h$i-$i", t = t, src = text, srcLang = "en", dstLang = "zh-CN", voice = voice)
+
+ fun clustererMatchesTheMac() {
+ val c = VoiceClusterer()
+ val a = unit(1); val b = unit(2)
+ equal(null, c.label(a, 1.5), "too short to start a voice")
+ equal(0, c.label(a, 3.0), "first voice")
+ equal(1, c.label(b, 3.0), "second voice")
+ equal(0, c.label(near(a, 7), 1.0), "joins the closest voice even when short")
+ equal(1, c.label(near(b, 8), 3.0), "the second again")
+ c.merge(1, 0)
+ equal(0, c.label(near(b, 9), 3.0), "after a merge, either voice goes to the one kept")
+ }
+
+ fun numbersWaitForTwoVoices() {
+ val old = SpeakerLabels.voices
+ SpeakerLabels.voices = true
+ try {
+ val lines = (0 until 5).map { them(it, 0) }.toMutableList()
+ equal(emptyMap<Int, Int>(), SpeakerLabels.voiceNumbers(lines), "one voice: still 对方")
+ lines += (0 until 4).map { them(10 + it, 1) } + them(20, 1, "ok")
+ equal(emptyMap<Int, Int>(), SpeakerLabels.voiceNumbers(lines), "a short line doesn't count")
+ lines += them(21, 1)
+ equal(mapOf(0 to 1, 1 to 2), SpeakerLabels.voiceNumbers(lines), "two voices with five lines")
+ } finally { SpeakerLabels.voices = old }
+ }
+
+ fun lingNamesNeedEvidence() {
+ val lines = mutableListOf<TranscriptLine>()
+ for (i in 0 until 5) { lines += them(2 * i, 0, t = 2.0 * i); lines += them(2 * i + 1, 1, t = 2.0 * i + 1) }
+ lines += them(40, 1, "Thanks so much, George, that was clear", t = 40.0)
+ val (found, refuted) = SpeakerNamer.read("{\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L11\"}," +
+ "{\"speaker\": 1, \"name\": \"Christina\", \"evidence\": \"L99\"}]}", lines)
+ equal("George", found[1]?.name, "named on the voice's own line")
+ check(found[1]!!.evidence.startsWith("00:40 “Thanks"), "evidence is the line: ${found[1]!!.evidence}")
+ equal(mapOf(0 to "Christina"), refuted.toMap(), "no evidence near the voice")
+ equal(0, SpeakerNamer.read("not json", lines).first.size, "not JSON")
+ check(SpeakerNamer.content(lines)!!.contains("说话人1"), "Ling sees the numbers")
+ check(SpeakerNamer.holds(found[1]!!, 1, lines), "the guess stands while its line does")
+
+ val store = SessionStore()
+ val s = store.begin()
+ lines.forEach { store.append(s.id, it) }
+ store.setVoiceGuesses(s.id, found, refuted)
+ equal(mapOf(2 to "George"), SpeakerLabels.names(store.get(s.id)!!), "the guess names speaker 2")
+ store.setVoiceGuesses(s.id, emptyMap(), mapOf(1 to "George"))
+ equal(null, store.get(s.id)!!.voiceGuesses, "a refuted guess goes")
+ }
+
+ fun notesPromptNamesTheVoices() {
+ val lines = (0 until 10).map { them(it, it % 2) } + them(20, null)
+ val p = NotesEngine.prompt(MeetingNotes(), lines, 0, "Chinese", false, numbers = SpeakerLabels.numbers(lines), names = mapOf(2 to "George"))
+ check(p.contains(" 说话人1] "), "a number")
+ check(p.contains("George] "), "a name")
+ check(p.contains("未识别] "), "a voice not on show")
+ check(NotesEngine.prompt(MeetingNotes(), lines, 0, "Chinese", false).contains("对方] "), "no voices: 对方")
+ }
+
+ /// Ming cuts "so we will ship" | "on Friday then." mid-sentence; `voices` says whose each half is.
+ private fun halves(voices: List<Int>): Pair<List<Pair<Int?, String>>, Int> {
+ val fake = Fake { body ->
+ if (body.contains("Ming-3.0-audio-flash")) {
+ val url = content(body, 1).arr()[0].obj()!!["audio_url"].obj()!!["url"] as String
+ reply(if (url.length < 60_000) "LANG: en\nORIGINAL: so we will ship\nTRANSLATION: 所以我们会发布"
+ else "LANG: en\nORIGINAL: on Friday then.\nTRANSLATION: 那就周五。")
+ } else reply("{}")
+ }
+ val order = voices.iterator()
+ val old = LingClient.spacing
+ LingClient.spacing = 0.05
+ try {
+ val ling = client(fake)
+ val store = SessionStore()
+ val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
+ // Each "voiceprint" is the voice to give: one dimension, and a clusterer stand-in below.
+ engine.speakers = object : SpeakerTagger(object : Voiceprinter {
+ override fun embed(samples: ShortArray) = synchronized(order) { floatArrayOf(order.next().toFloat()) }
+ }) { override fun label(vector: FloatArray?, seconds: Double) = vector?.get(0)?.toInt() }
+ val heard = AtomicInteger()
+ engine.onVoice = { heard.incrementAndGet() }
+ val src = PcmAudioSource({ concat(tone(1.0), silence(0.8), tone(1.4), silence(1.0)) }, speed = 0.0)
+ val ended = CountDownLatch(1)
+ src.onEnded = { ended.countDown() }
+ engine.start(src, "file")
+ ended.await()
+ Thread.sleep(200)
+ engine.stop()
+ return store.get(engine.sessionId!!)!!.lines.map { it.voice to it.src } to heard.get()
+ } finally { LingClient.spacing = old }
+ }
+
+ fun aHalfSentenceJoinsOnlyTheSameVoice() {
+ val (lines, heard) = halves(listOf(1, 2))
+ equal(listOf(1 to "so we will ship", 2 to "on Friday then."), lines, "two voices, two lines")
+ equal(2, heard, "each voiced line asks for names")
+ equal(listOf(1 to "so we will ship on Friday then."), halves(listOf(1, 1)).first, "the same voice: one sentence")
+ }
+
+ fun slowVoiceprintsNeverHoldSubtitlesBack() {
+ val fake = Fake { body ->
+ if (body.contains("Ming-3.0-audio-flash")) reply("LANG: en\nORIGINAL: We should ship it on Friday.\nTRANSLATION: 我们周五发布。")
+ else reply("{}")
+ }
+ val old = LingClient.spacing
+ LingClient.spacing = 0.01
+ try {
+ val ling = client(fake)
+ val store = SessionStore()
+ val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
+ engine.speakers = object : SpeakerTagger(object : Voiceprinter {
+ override fun embed(samples: ShortArray): FloatArray { Thread.sleep(600); return floatArrayOf(1f) } // a phone that can't keep up
+ }) { override fun label(vector: FloatArray?, seconds: Double) = if (vector == null) null else 0 }
+ val src = PcmAudioSource({ concat(*Array(5) { concat(tone(1.0), silence(1.0)) }) }, speed = 0.0)
+ val ended = CountDownLatch(1)
+ src.onEnded = { ended.countDown() }
+ engine.start(src, "file")
+ ended.await()
+ Thread.sleep(2500)
+ engine.stop()
+ val voices = store.get(engine.sessionId!!)!!.lines.map { it.voice }
+ equal(5, voices.size, "every line")
+ check(null in voices, "some lines went unlabelled rather than waiting: $voices")
+ check(0 in voices, "the others have their voice: $voices")
+ } finally { LingClient.spacing = old }
+ }
+
// MARK: Meeting end (MeetingEndTests.swift, the same cases)
private val zoom = mapOf("us.zoom.xos" to "Zoom")
diff --git a/android/core/src/main/kotlin/cicada/Export.kt b/android/core/src/main/kotlin/cicada/Export.kt
index 95589eb..ed4b04e 100644
--- a/android/core/src/main/kotlin/cicada/Export.kt
+++ b/android/core/src/main/kotlin/cicada/Export.kt
@@ -10,8 +10,7 @@ import java.util.zip.ZipOutputStream
/// What the transcript shows for the other side's lines (the Mac's SpeakerLabels, SpeakerID.swift).
/// A voice gets a number only once it has `SHOWN_AFTER` substantive lines, and only when at least
/// two voices have, so a one-to-one call stays 对方. Numbers follow the order voices got there.
-/// Android doesn't tell voices apart itself yet (no voiceprint runtime in the framework): the
-/// voices come from records made on the Mac or Windows, and the names the user gives here.
+/// The voices come from SpeakerTagger (Speakers.kt) or records made on another platform.
object SpeakerLabels {
const val SHOWN_AFTER = 5
diff --git a/android/core/src/main/kotlin/cicada/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.kt
index 58df4d2..14ec1d2 100644
--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt
+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt
@@ -34,6 +34,18 @@ class ListenEngine(
private var candidate: String? = null
private var candidateVotes = 0
private val listeners = mutableListOf<() -> Unit>()
+ /// One thread records delivered lines, so lines (and their voices) go in strictly in segment order.
+ private val deliverLock = Any()
+
+ /// 说话人识别 (Speakers.kt), set by the app; null or unavailable leaves every line 对方.
+ @Volatile var speakers: SpeakerTagger? = null
+ /// A line got a voice (the meeting's id): the app asks Ling for names.
+ @Volatile var onVoice: ((String) -> Unit)? = null
+ /// Voiceprints one at a time beside Ming (each already uses up to four cores).
+ private val voicePool = Executors.newSingleThreadExecutor { r -> Thread(r, "Voiceprints").apply { isDaemon = true } }
+ private val voiceprints = HashMap<Int, Future<FloatArray?>>()
+ private var voicesWaiting = 0
+ private val voicesOn: Boolean get() = settings.speakerVoices && speakers?.available == true
@Volatile var listening = false; private set
@Volatile var sessionId: String? = null; private set
@@ -144,13 +156,14 @@ class ListenEngine(
sessionId = session.id
sourceKind = kind
synchronized(gate) {
- done.clear(); segments.clear(); inFlight.clear()
+ done.clear(); segments.clear(); inFlight.clear(); voiceprints.clear()
nextToDeliver = 1; lineCount = 0; last = null; lastEnd = 0.0
hint = null; candidate = null; candidateVotes = 0; problem = null; problemKind = null; serverErrors = 0
}
holding = false; saying = false; muted = false; sayProblem = null; saidCount = 0
heardSeconds = 0.0; peak = 0.0
notes.begin(session.id)
+ speakers?.reset()
val segmenter = Segmenter()
segmenter.onSegment = ::send
val queue = LinkedBlockingQueue<ShortArray>()
@@ -274,6 +287,23 @@ class ListenEngine(
}
private fun send(seg: Segment) {
+ if (voicesOn) {
+ // Subtitles wait for a line's voice, so on a phone too slow to keep up a line goes
+ // unlabelled (对方) rather than every subtitle falling further behind.
+ val behind = synchronized(gate) { (voicesWaiting >= 2).also { if (!it) voicesWaiting++ } }
+ if (behind) Log.d("speakers: voiceprints behind, segment ${seg.index} left unlabelled")
+ else {
+ val f = voicePool.submit<FloatArray?> {
+ val started = System.currentTimeMillis()
+ try {
+ speakers?.embed(seg.samples).also {
+ Log.d("speakers: segment ${seg.index} ${"%.1f".format(seg.seconds)}s voiceprint in ${System.currentTimeMillis() - started} ms")
+ }
+ } finally { synchronized(gate) { voicesWaiting-- } }
+ }
+ synchronized(gate) { voiceprints[seg.index] = f }
+ }
+ }
val lang = synchronized(gate) { segments[seg.index] = seg; hint }
// Timing only (never text): where the segment sits in the audio, to measure delay.
Log.d("listen: segment ${seg.index} sent at ${"%.2f".format(seg.start)}+${"%.2f".format(seg.seconds)}")
@@ -316,18 +346,33 @@ class ListenEngine(
/// Hands finished segments on in order: one slow reply holds back those after it.
private fun deliver() {
val ready = mutableListOf<Pair<Segment, Heard?>>()
- synchronized(gate) {
- while (done.containsKey(nextToDeliver)) {
- val heard = done.remove(nextToDeliver)
- ready.add(segments.remove(nextToDeliver)!! to heard)
- nextToDeliver++
+ synchronized(deliverLock) {
+ synchronized(gate) {
+ while (done.containsKey(nextToDeliver)) {
+ val heard = done.remove(nextToDeliver)
+ ready.add(segments.remove(nextToDeliver)!! to heard)
+ nextToDeliver++
+ }
+ }
+ for ((seg, heard) in ready) {
+ val print = synchronized(gate) { voiceprints.remove(seg.index) }
+ if (heard != null) record(seg, heard, voice(print, seg, heard))
}
}
- for ((seg, heard) in ready) if (heard != null) record(seg, heard)
if (ready.isNotEmpty()) changed()
}
- private fun record(seg: Segment, heard: Heard) {
+ /// The segment's voice, or null when unsure. A line with hardly a letter ("." from a breath or
+ /// a click) gets no voiceprint; like the Mac, every labelled segment counts towards its voice.
+ private fun voice(print: Future<FloatArray?>?, seg: Segment, heard: Heard): Int? {
+ if (print == null || heard.original.count { it.isLetter() } < 2) return null
+ val vector = try { print.get(20, TimeUnit.SECONDS) } catch (e: Exception) {
+ Log.d("speakers: voiceprint failed ${e.javaClass.simpleName}"); return null
+ }
+ return speakers?.label(vector, seg.seconds)
+ }
+
+ private fun record(seg: Segment, heard: Heard, voice: Int?) {
val id = sessionId ?: return
val target = settings.targetFor(heard.lang)
// The meeting's language moves only after two segments agree, so one misheard stretch
@@ -345,14 +390,15 @@ class ListenEngine(
var joined = false
synchronized(gate) {
val prev = last
- if (prev != null && continues(prev, seg.start - lastEnd, heard)) {
+ // Two voices never share a line: a half sentence joins only the same voice (or an unknown one).
+ if (prev != null && continues(prev, seg.start - lastEnd, heard) && (voice == null || prev.voice == null || voice == prev.voice)) {
prev.src = join(prev.src, heard.original, heard.lang)
prev.dst = if (prev.dst == null || heard.translation == null) null else join(prev.dst!!, heard.translation, target)
line = prev
joined = true
} else {
line = TranscriptLine(id = "h${++lineCount}-${seg.index}", t = seg.start, speaker = "them",
- src = heard.original, dst = heard.translation, srcLang = heard.lang, dstLang = target)
+ src = heard.original, dst = heard.translation, srcLang = heard.lang, dstLang = target, voice = voice)
last = line
}
lastEnd = seg.start + seg.seconds
@@ -361,6 +407,7 @@ class ListenEngine(
// A line the hear model translated itself: finished sentences are being translated again.
if (!joined && heard.translation != null) translator.sentencesUntranslated = false
if (joined) store.replace(id, copy) else store.append(id, copy)
+ if (voice != null) onVoice?.invoke(id)
onWords?.invoke()
// A joined sentence is translated again as a whole; a line Ming didn't translate gets text translation.
diff --git a/android/core/src/main/kotlin/cicada/Models.kt b/android/core/src/main/kotlin/cicada/Models.kt
index e8cc1d7..8a28ee0 100644
--- a/android/core/src/main/kotlin/cicada/Models.kt
+++ b/android/core/src/main/kotlin/cicada/Models.kt
@@ -26,7 +26,7 @@ class TranscriptLine(
var dst: String? = null,
var srcLang: String = "",
var dstLang: String = "",
- /// Experimental voice id on the Mac; Android doesn't tell voices apart yet.
+ /// The other side's voice, as SpeakerTagger grouped it (null: not told apart).
var voice: Int? = null,
/// "room": heard by the Mac's room microphone in a 电脑和会议室 meeting; kept so a Mac record
/// opened here keeps its 现场 / 线上.
diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.kt
index d67399a..4c84752 100644
--- a/android/core/src/main/kotlin/cicada/Notes.kt
+++ b/android/core/src/main/kotlin/cicada/Notes.kt
@@ -118,9 +118,12 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
// the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and
// the notes stopped updating. The final pass still rewrites everything once.
val frozen = if (final) 0 else maxOf(0, base.topics.size - EDITABLE_TOPICS)
- val prompt = prompt(base, lines, from, lang, final, frozen = frozen)
+ // Voices told apart go as 说话人N, or the name they've been given (notes then say "George").
+ val numbers = SpeakerLabels.numbers(lines)
+ val names = SpeakerLabels.names(session)
+ val prompt = prompt(base, lines, from, lang, final, frozen = frozen, numbers = numbers, names = names)
val startedAt = lines.firstOrNull()?.t ?: 0.0
- var next: MeetingNotes? = if (final) longFinal(lines, lang, startedAt) else null
+ var next: MeetingNotes? = if (final) longFinal(lines, numbers, names, lang, startedAt) else null
for (attempt in 1..(if (final) 2 else 1)) {
if (next != null) break
val raw = ling.chat(prompt, "Update the notes. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0, patient = final)
@@ -163,7 +166,8 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
/// A long meeting's final pass: each part noted on its own, all at once, then merged into one.
/// null when a step fails: the caller then makes one pass over the whole transcript, as before.
- private fun longFinal(lines: List<TranscriptLine>, lang: String, startedAt: Double): MeetingNotes? {
+ private fun longFinal(lines: List<TranscriptLine>, numbers: Map<String, Int>, names: Map<Int, String>,
+ lang: String, startedAt: Double): MeetingNotes? {
val parts = parts(lines)
if (parts.size <= 1) return null
val started = System.currentTimeMillis()
@@ -173,7 +177,8 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
val pool = Executors.newFixedThreadPool(parts.size) { r -> Thread(r, "NotesPart").apply { isDaemon = true } }
val replies = try {
pool.invokeAll(parts.mapIndexed { i, range ->
- val prompt = prompt(MeetingNotes(), lines.subList(0, range.last + 1), range.first, lang, final = true, part = i + 1 to parts.size)
+ val prompt = prompt(MeetingNotes(), lines.subList(0, range.last + 1), range.first, lang, final = true,
+ numbers = numbers, names = names, part = i + 1 to parts.size)
Callable {
try {
ling.chat(prompt, "Write the notes for this part. Write them in $lang.", Priority.Notes, json = true, maxTokens = 6000, timeout = 90.0)
@@ -307,11 +312,13 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
/// `frozen`: how many first topics a live update leaves alone (sent as a list, not returned).
/// `part`: in a long meeting's final pass, which part `from until lines.size` is (1-based, of).
+ /// `numbers` / `names`: voices told apart (line id → 说话人N) and the names given to them.
fun prompt(notes: MeetingNotes, lines: List<TranscriptLine>, from: Int, language: String, final: Boolean,
- frozen: Int = 0, part: Pair<Int, Int>? = null): String {
- fun line(i: Int): String {
+ frozen: Int = 0, part: Pair<Int, Int>? = null,
+ numbers: Map<String, Int> = emptyMap(), names: Map<Int, String> = emptyMap()): String { fun line(i: Int): String {
val l = lines[i]
- val who = if (l.speaker == "me") "你" else "对方"
+ val n = numbers[l.id]
+ val who = if (l.speaker == "me") "你" else if (n != null) names[n] ?: "说话人$n" else if (numbers.isEmpty()) "对方" else "未识别"
return "[L${i + 1} ${Languages.clock(l.t)} $who] ${l.src}"
}
val current = if (notes.isEmpty) "{}" else compactJson(notes, frozen)
diff --git a/android/core/src/main/kotlin/cicada/SessionStore.kt b/android/core/src/main/kotlin/cicada/SessionStore.kt
index 6bf910f..ae5b212 100644
--- a/android/core/src/main/kotlin/cicada/SessionStore.kt
+++ b/android/core/src/main/kotlin/cicada/SessionStore.kt
@@ -100,6 +100,18 @@ class SessionStore(loadNow: Boolean = true) {
s.voiceNames = names
}
+ /// Ling's latest guesses (SpeakerNamer); earlier ones stay for voices it no longer mentions,
+ /// unless it now named them without evidence (refuted, voice → name): then that earlier name goes too.
+ fun setVoiceGuesses(id: String, guesses: Map<Int, VoiceGuess>, refuted: Map<Int, String> = emptyMap()) {
+ if (guesses.isEmpty() && refuted.isEmpty()) return
+ mutate(id) { s ->
+ val all = (s.voiceGuesses ?: emptyMap()).toMutableMap()
+ for ((v, name) in refuted) if (v !in guesses && all[v.toString()]?.name == name) all.remove(v.toString())
+ for ((v, g) in guesses) all[v.toString()] = g
+ s.voiceGuesses = all.ifEmpty { null }
+ }
+ }
+
/// Fields set once around a meeting (its recording, an imported file's name and progress).
fun update(id: String, change: (Session) -> Unit) = mutate(id, change)
diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.kt
index b70351a..c134975 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -39,7 +39,7 @@ class AppSettings(
var silenceEnd: String = "prompt",
/// 多久算没人说话, in minutes: 5, 10, 15 or 30.
var silenceMinutes: Double = 10.0,
- /// 说话人识别: number the other side's voices in records and exports (the Mac's speakerVoices).
+ /// 说话人识别: tell the other side's voices apart and number them (the Mac's speakerVoices).
var speakerVoices: Boolean = true,
/// 保存会议录音: keep what was heard as system.m4a beside the record (the Mac's recordAudio).
var recordAudio: Boolean = true,
diff --git a/android/core/src/main/kotlin/cicada/Speakers.kt b/android/core/src/main/kotlin/cicada/Speakers.kt
new file mode 100644
index 0000000..a2beddb
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/Speakers.kt
@@ -0,0 +1,200 @@
+package cicada
+
+import kotlin.math.sqrt
+
+/// 说话人识别: telling the other side's voices apart (SpeakerID.swift; linux/cicada/core/speakers.py).
+/// Each heard line's audio becomes a voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0),
+/// voiceprints are grouped as they arrive, and a voice is only shown once it has a few lines
+/// (SpeakerLabels). The thresholds are the Mac's, tuned on AMI meetings.
+///
+/// The model runs in linux/native/voiceprint.c, built into the app with the NDK: the app gives a
+/// `Voiceprinter`; this plain-JVM side only groups. Without one the feature is unavailable and
+/// listening carries on as before.
+interface Voiceprinter {
+ /// A unit-length voiceprint of 16 kHz mono samples, or null (too short, or it failed).
+ fun embed(samples: ShortArray): FloatArray?
+}
+
+/// Groups voiceprints as lines arrive, never revising a line already labelled. A line joins the
+/// closest voice when similar enough; a long line unlike every voice starts a new one; anything
+/// else stays unlabelled (对方). (VoiceClusterer, SpeakerID.swift.)
+class VoiceClusterer {
+ private val sums = ArrayList<FloatArray>()
+
+ /// The user said two voices are one: later lines like either go to `into`.
+ fun merge(from: Int, into: Int) {
+ if (from !in sums.indices || into !in sums.indices || from == into) return
+ val a = sums[into]; val b = sums[from]
+ for (i in a.indices) a[i] += b[i]
+ b.fill(0f) // never the closest again
+ }
+
+ fun label(v: FloatArray, seconds: Double): Int? {
+ var best = -1; var bestSim = -1f
+ for ((i, s) in sums.withIndex()) {
+ var dot = 0f; var sq = 0f
+ for (k in s.indices) { dot += v[k] * s[k]; sq += s[k] * s[k] }
+ val sim = dot / maxOf(sqrt(sq), 1.1920929e-07f)
+ if (sim > bestSim) { bestSim = sim; best = i }
+ }
+ if (best >= 0 && bestSim >= JOIN) {
+ val s = sums[best]
+ for (k in s.indices) s[k] += v[k]
+ return best
+ }
+ if (seconds >= NEW_SECONDS && (sums.isEmpty() || bestSim < START_NEW)) {
+ sums.add(v.copyOf())
+ return sums.size - 1
+ }
+ return null
+ }
+
+ companion object {
+ const val NEW_SECONDS = 2.0
+ const val JOIN = 0.5f
+ const val START_NEW = 0.5f
+ }
+}
+
+/// Voiceprints for listening: `embed` runs on the engine's voice thread while Ming hears the same
+/// segment; `label` is called in segment order.
+open class SpeakerTagger(private val voiceprints: Voiceprinter?) {
+ private val gate = Any()
+ private var clusterer = VoiceClusterer()
+
+ val available: Boolean get() = voiceprints != null
+
+ /// A new meeting: forget the voices of the last one.
+ fun reset() = synchronized(gate) { clusterer = VoiceClusterer() }
+
+ fun merge(from: Int, into: Int) = synchronized(gate) { clusterer.merge(from, into) }
+
+ fun embed(samples: ShortArray): FloatArray? {
+ if (samples.size < MIN_SECONDS * Segmenter.RATE) return null
+ return voiceprints?.embed(samples)
+ }
+
+ open fun label(vector: FloatArray?, seconds: Double): Int? {
+ vector ?: return null
+ return synchronized(gate) { clusterer.label(vector, seconds) }
+ }
+
+ companion object { const val MIN_SECONDS = 0.5 }
+}
+
+/// Names from the conversation (SpeakerNameGuess, SpeakerNamer): asks Ling on its own once two
+/// voices are on show, again every 20 lines, and once more when the meeting ends. Guesses go
+/// straight into the meeting (voiceGuesses); the user corrects them.
+class SpeakerNamer(private val ling: LingClient, private val store: SessionStore) {
+ private val gate = Any()
+ private val busy = HashSet<String>()
+ private val asked = HashMap<String, Int>()
+
+ fun guess(id: String, force: Boolean = false) {
+ val s = store.get(id) ?: return
+ if (!ling.hasKey) return
+ val text: String
+ val lines: List<TranscriptLine>
+ synchronized(gate) {
+ lines = store.lines(id)
+ if (id in busy || !(force || lines.size >= (asked[id] ?: -1000) + 20)) return
+ text = content(lines) ?: return
+ val numbers = SpeakerLabels.voiceNumbers(lines)
+ if (numbers.keys.all { s.voiceNames?.get(it.toString()) != null }) return // everyone already has the user's name
+ busy.add(id)
+ asked[id] = lines.size
+ }
+ Thread({
+ try {
+ val reply = ling.chat(text, INSTRUCTION, Priority.Notes, json = true, maxTokens = 300)
+ val (found, refuted) = read(reply, lines)
+ for ((key, g) in s.voiceGuesses ?: emptyMap()) {
+ val v = key.toIntOrNull() ?: continue
+ if (v !in found && !holds(g, v, lines)) refuted[v] = g.name
+ }
+ store.setVoiceGuesses(id, found, refuted)
+ Log.d("speakers: names ${found.size} found, ${refuted.size} without evidence")
+ } catch (e: LingException) {
+ Log.d("speakers: names, ling failed ${e.message}")
+ } catch (e: Exception) {
+ Log.d("speakers: names failed ${e.javaClass.simpleName}")
+ } finally {
+ synchronized(gate) { busy.remove(id) }
+ }
+ }, "SpeakerNames").apply { isDaemon = true }.start()
+ }
+
+ companion object {
+ /// Ling's prompt, word for word the Mac's.
+ const val INSTRUCTION = "Who are the people labelled 说话人N? Name one only when the transcript makes it clear: they " +
+ "introduce themselves on a line labelled with their own 说话人N; someone addresses them by name just " +
+ "before or after they speak (\"Thanks, George\" right after 说话人1's answer: 说话人1 is George); " +
+ "or others name them as they speak. A name on a 对方 line, or far from any line of 说话人N (an advert, " +
+ "a clip, people introducing themselves on another show), is not theirs. Speech recognition writes " +
+ "names by ear and often misspells them: for a public figure (an official, an executive, a presenter) " +
+ "recognisable from the name and what is said, write the name as the news spells it (\"Jensen Hwang\" " +
+ "→ \"Jensen Huang\"); otherwise as written. Leave out anyone " +
+ "you are unsure of. Reply as JSON: {\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L12\"}]}, " +
+ "the evidence being the line with the name; an empty list if none. Check each name's spelling before replying."
+
+ /// "Okay, Amos, thank you" comes right after Amos's last words.
+ const val EVIDENCE_REACH = 2
+
+ /// The transcript as Ling sees it, newest 400 lines, with speaker labels; null when no voices are shown.
+ fun content(lines: List<TranscriptLine>): String? {
+ val numbers = SpeakerLabels.voiceNumbers(lines)
+ if (numbers.isEmpty()) return null
+ val sb = StringBuilder("Meeting transcript. Speakers: 你 = the user; 说话人N = one person on the other side, told apart by voice; " +
+ "对方 = someone on the other side, not identified.\n")
+ for ((i, l) in lines.takeLast(400).withIndex()) {
+ val n = if (l.speaker == "them") l.voice?.let { numbers[it] } else null
+ val who = if (l.speaker == "me") "你" else if (n != null) "说话人$n" else "对方"
+ sb.append("[L${i + 1} ${Languages.clock(l.t)} $who] ${l.src}\n")
+ }
+ return sb.toString()
+ }
+
+ /// (found: voice → guess, refuted: voice → name). A name given on a line the voice neither
+ /// said nor spoke next to is refuted; a name Ling gives two voices goes to the one with more lines.
+ fun read(reply: String, all: List<TranscriptLine>): Pair<MutableMap<Int, VoiceGuess>, MutableMap<Int, String>> {
+ val found = LinkedHashMap<Int, VoiceGuess>(); val refuted = LinkedHashMap<Int, String>()
+ val list = try { Json.parse(reply).obj()?.get("speakers").arr() } catch (_: Exception) { null } ?: return found to refuted
+ val voiceOf = SpeakerLabels.voiceNumbers(all).entries.associate { (v, n) -> n to v }
+ val lines = all.takeLast(400)
+ fun count(v: Int) = all.count { it.voice == v }
+ for (item in list) {
+ val o = item.obj() ?: continue
+ val n = o["speaker"]?.toString()?.removeSuffix(".0")?.toIntOrNull() ?: continue
+ val v = voiceOf[n] ?: continue
+ val name = o["name"].str()?.trim() ?: continue
+ if (name.isEmpty() || name.length > 40) continue
+ val e = o["evidence"]?.toString() ?: ""
+ val i = (e.dropWhile { !it.isDigit() }.takeWhile { it.isDigit() }.toIntOrNull() ?: 0) - 1
+ val near = if (i in lines.indices) lines.subList(maxOf(0, i - EVIDENCE_REACH), minOf(lines.size, i + EVIDENCE_REACH + 1)) else emptyList()
+ if (near.none { it.speaker == "them" && it.voice == v }) { refuted[v] = name; continue }
+ val other = found.entries.firstOrNull { it.value.name == name }?.key
+ if (other != null) {
+ if (count(other) >= count(v)) continue
+ found.remove(other)
+ }
+ val l = lines[i]
+ val quote = if (l.src.length > 60) l.src.take(60) + "…" else l.src
+ found[v] = VoiceGuess(name, "${Languages.clock(l.t)} “$quote”")
+ }
+ return found to refuted
+ }
+
+ /// Whether a stored guess still stands: its evidence line is found again and the voice speaks there.
+ fun holds(g: VoiceGuess, v: Int, lines: List<TranscriptLine>): Boolean {
+ if (!g.evidence.contains("“")) return true
+ val at = g.evidence.substringBefore("“").trim()
+ val quote = g.evidence.substringAfter("“").removeSuffix("”").substringBefore("…")
+ for ((i, l) in lines.withIndex()) {
+ if (Languages.clock(l.t) == at && l.src.startsWith(quote))
+ return lines.subList(maxOf(0, i - EVIDENCE_REACH), minOf(lines.size, i + EVIDENCE_REACH + 1))
+ .any { it.speaker == "them" && it.voice == v }
+ }
+ return true
+ }
+ }
+}
diff --git a/android/scripts/install-sdk.sh b/android/scripts/install-sdk.sh
index 117579c..1b47809 100755
--- a/android/scripts/install-sdk.sh
+++ b/android/scripts/install-sdk.sh
@@ -1,9 +1,9 @@
#!/bin/bash
# One-time toolchain for the Android app, all under ~/.cicada-android (no sudo, nothing system-wide):
-# a JDK 21, Gradle, the Android SDK (platform, build tools, emulator) and an arm64 system image for
-# the test emulator. Versions are pinned and every download is checked against its published
-# checksum before it is unpacked. Re-running skips what is already there. --old also makes
-# `cicada29`, an Android 10 emulator (the oldest Android the app supports).
+# a JDK 21, Gradle, the Android SDK (platform, build tools, the NDK for the voiceprint library,
+# emulator) and an arm64 system image for the test emulator. Versions are pinned and every download
+# is checked against its published checksum before it is unpacked. Re-running skips what is already
+# there. --old also makes `cicada29`, an Android 10 emulator (the oldest Android the app supports).
set -euo pipefail
D="$HOME/.cicada-android"; mkdir -p "$D"; cd "$D"
JDK=21.0.13_9; JDK_TAG="jdk-21.0.13%2B9"
@@ -12,6 +12,8 @@ JDK_SHA_X64=9aa1d1c17ae5467a022679e7e0af5c00797d94ac462ed1a46f4db07a8a34a6dd
GRADLE=9.8.2; GRADLE_SHA=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607
CLT=15641748; CLT_SHA1=b62a5d8cf63ded173b47be867be4ee058ceda6df
API=36; BUILD_TOOLS=36.0.0
+# The NDK builds 说话人识别's voiceprint library (linux/native/voiceprint.c); app/build.gradle.kts pins the same.
+NDK=29.0.14206865
# fetch <url> <file> <sha256|sha1:…>: download, then refuse anything that doesn't match.
fetch() {
@@ -43,7 +45,7 @@ sm=sdk/cmdline-tools/latest/bin/sdkmanager; avd=sdk/cmdline-tools/latest/bin/avd
yes | "$sm" --licenses >/dev/null || true
images=("system-images;android-$API;google_apis;arm64-v8a")
[ "${1:-}" = --old ] && images+=("system-images;android-29;google_apis;arm64-v8a")
-"$sm" "platform-tools" "platforms;android-$API" "build-tools;$BUILD_TOOLS" "emulator" "${images[@]}" >/dev/null
+"$sm" "platform-tools" "platforms;android-$API" "build-tools;$BUILD_TOOLS" "ndk;$NDK" "emulator" "${images[@]}" >/dev/null
"$avd" list avd -c | grep -qx cicada || echo no | "$avd" create avd -n cicada -k "${images[0]}" -d pixel_7 >/dev/null
if [ "${1:-}" = --old ] && ! "$avd" list avd -c | grep -qx cicada29; then
echo no | "$avd" create avd -n cicada29 -k "${images[1]}" -d pixel_4 >/dev/null
diff --git a/docs/android-plan.md b/docs/android-plan.md
index caeb31e..d6a9948 100644
--- a/docs/android-plan.md
+++ b/docs/android-plan.md
@@ -21,7 +21,7 @@ Android 10 起可以采集其他 app 播放的声音(`AudioPlaybackCapture`)
面对面里的“我说”:按住说话,松开后 Ming 译成对方的语言,用系统的文字转语音读出来;读的时候不把手机自己的声音当成对方的话。说进别的 app 的通话做不到(Android 没有虚拟麦克风),不做。
-第一版不做:说话人识别、离线识别、录音文件。
+第一版不做:离线识别、录音文件。说话人识别后来补上了:用 Linux 版自己写的 C 推理(`linux/native/voiceprint.c`),由 NDK 编进 app,和 Mac 同一个声纹模型、同样的阈值。
最低系统 Android 10(API 29),目标 API 36。
@@ -30,8 +30,8 @@ Android 10 起可以采集其他 app 播放的声音(`AudioPlaybackCapture`)
| 决策 | 选择 | 原因 |
|---|---|---|
| 代码放哪 | 同仓库 `android/` | 和 Windows 一样:提示词、记录格式、文案要跟 Mac 对照修改 |
-| 技术栈 | Kotlin + Android 框架自带的 View,代码写界面;不用 AndroidX、Compose、协程库 | 对应 Mac / Windows 的“不用第三方依赖”。只用 Kotlin 标准库、`java.*` 和 `android.*` |
-| 构建 | Gradle + Android Gradle Plugin,工具链由 `scripts/install-sdk.sh` 装到 `~/.cicada-android`(JDK、Gradle、SDK、模拟器),不用 Android Studio | 和 Windows 的 `install-dotnet.sh` 一样,不用 sudo,命令行就能编译和测试 |
+| 技术栈 | Kotlin + Android 框架自带的 View,代码写界面;不用 AndroidX、Compose、协程库 | 对应 Mac / Windows 的“不用第三方依赖”。只用 Kotlin 标准库、`java.*` 和 `android.*`;唯一的原生代码是说话人识别用的自己写的 C(`linux/native/voiceprint.c`) |
+| 构建 | Gradle + Android Gradle Plugin,工具链由 `scripts/install-sdk.sh` 装到 `~/.cicada-android`(JDK、Gradle、SDK、NDK、模拟器),不用 Android Studio | 和 Windows 的 `install-dotnet.sh` 一样,不用 sudo,命令行就能编译和测试 |
| 引擎放哪 | `android/core` 是纯 JVM 的 Kotlin 库,不依赖 Android | 在 Mac 上直接跑单元测试和真实调用(`cli`),像 `Cicada.Core` |
| JSON | 自己写的小解析器和写出器(`Json.kt`) | `org.json` 只在 Android 上有、不排序 key;自己写才能和 Mac 的 `session.json` 逐字节一致 |
| 语音识别 | Ming 分段识别,同 Windows | 同一个 Ling key;M0 已在 Windows 方案里测过延迟和准确率 |
@@ -106,7 +106,7 @@ MediaProjection → AudioPlaybackCapture(排除知了自己) ┐
| **M1 字幕** | 前台服务、两种声音来源、分段 → Ming、悬浮字幕 | 模拟器里播放的视频声音变成字幕;截图里看不到悬浮窗 |
| **M2 纪要和记录** | 纪要引擎、`session.json`、会议记录、引导、设置、四种界面语言 | Mac 生成的记录 Android 能打开,写出去逐字节一致 |
| **M3 能发布** | 签名的 APK(GitHub Release 下载,校验 SHA-256)、官网入口、电池优化引导、真机测试(至少一台国产手机) | 一台干净的真机从下载到第一次出字幕不用电脑 |
-| 以后 | 应用商店、录音、流式识别、说话人识别 | 按反馈排 |
+| 以后 | 应用商店、录音、流式识别 | 按反馈排 |
## 风险
diff --git a/site/changelog.json b/site/changelog.json
index 22b24f2..d643453 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -84,6 +84,14 @@
"title": "“听哪里”换成一个“打开麦克风”按钮,在纪要窗口和托盘或顶栏菜单里都能点;戴耳机或电脑放音乐时,桌边的话也能记下。",
"text": "电脑里的声音一直在听,打开麦克风就把桌边的人加进同一场会议,每次启动都是关着的。知了会测出扬声器的声音有没有传到麦克风:传到了,线上有人说话时桌边先不听;戴耳机或用会议麦克风时不用避让,两边同时说话都能记下;电脑放音乐时也不避让。不再问“在会议室里开会?”和“线上也有人?”。"
},
+ {
+ "kind": "new",
+ "platforms": [
+ "android"
+ ],
+ "title": "Android 也能按声音分出说话人了。",
+ "text": "每句话的声音在手机上比对,标出说话人 1、2…,有 Ling key 时还会从对话里认出名字;和 Mac 用同一个声纹模型。"
+ },
{
"kind": "fixed",
"platforms": [