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(speakers): remember known voices across meetings

clementchen9a17476dca17
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index 36e7a13..3879053 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -1467,3 +1467,51 @@
"没存到文件夹 ·" = "Not saved to the folder ·";
"整理好后存到 %@" = "Saves to %@ once the notes are ready";
"在访达中显示" = "Show in Finder";
+
+/* Voiceprint memory */
+"声纹库" = "Voice library";
+"只保存在这台 Mac;删除后,以前的会议记录不会受影响。" = "Only on this Mac. Deleting a profile does not change past meeting records.";
+"还没有记住的人" = "No voices saved yet";
+"在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。" = "In a meeting, open a speaker and choose Remember this voice; next time they will be recognized.";
+"名字" = "Name";
+"%lld 段样本 · 最近 %@" = "%lld samples · last seen %@";
+"改名" = "Rename";
+"共 %lld 个人" = "%lld people";
+"全部删除" = "Delete all";
+"删除“%@”的声纹?" = "Delete the voiceprint for “%@”?";
+"之后的会议不会再自动认出这个人;已经生成的记录保持原样。" = "Future meetings won't recognize this person automatically. Existing records stay unchanged.";
+"删除全部声纹?" = "Delete all voiceprints?";
+"之后所有会议都不会再自动认出人;已有记录保持原样。" = "All future meetings will stop recognizing people automatically. Existing records stay unchanged.";
+"还没在新会议里出现" = "Not seen in a new meeting yet";
+"记住说话人" = "Remember speakers";
+"按本机声纹认出以前见过的人;不会上传声音" = "Recognize people you've met by voice, on this Mac; audio is never uploaded";
+"%lld 个人" = "%lld people";
+"管理" = "Manage";
+"声纹库:可能是 %@(%lld%%)" = "Voice library: possibly %@ (%lld%%)";
+"声音像,但还不够确定。确认后,下次会议会直接认出。" = "It sounds similar, but isn't certain yet. Confirming makes the next meeting recognize them.";
+"是 TA" = "Yes, that's them";
+"不是" = "No";
+"声纹库:%@" = "Voice library: %@";
+"这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。" = "This meeting was labelled with this voiceprint. If it's wrong, disconnect it for this meeting only; the profile stays.";
+"更新声纹" = "Update voiceprint";
+"记住这个声音" = "Remember this voice";
+"正在记住…" = "Remembering…";
+"下次会议自动认出" = "Recognized automatically next time";
+"需要 3 句以上发言;声纹只保存在这台 Mac" = "Needs at least 3 sentences; the voiceprint stays on this Mac";
+"先给这个人起个名字" = "Name this person first";
+"在“是谁”里输入名字后,再记住这个声音。" = "Type a name under Who, then remember this voice.";
+"没有可用的录音" = "No usable recording";
+"打开“保存会议录音”,或用导入的录音文件建立声纹。" = "Turn on Save meeting audio, or use an imported recording to create a voiceprint.";
+"记住“%@”的声音?" = "Remember the voice of “%@”?";
+"声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。" = "The voiceprint stays only on this Mac and is used to recognize this person in future meetings. You can delete it from the voice library anytime.";
+"记住" = "Remember";
+"不用" = "Not now";
+"这个声音还不够清楚" = "This voice isn't clear enough";
+"换一段更长、更安静的发言再试。" = "Try a longer, quieter stretch of speech.";
+"没记住这个声音" = "Couldn't remember this voice";
+"这场会议没有可用的录音,先打开保存会议录音再试" = "This meeting has no usable recording. Turn on Save meeting audio first.";
+"这个人的发言太少,至少要有 3 句、4 秒左右的声音" = "This person has too little speech. At least 3 sentences and about 4 seconds are needed.";
+"声纹模型加载失败,稍后再试" = "Couldn't load the voiceprint model. Try again later.";
+"已认出 %@" = "Recognized %@";
+"这次不再按声纹认人" = "Stop recognizing by voice for this meeting";
+"知道了" = "OK";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index 45d0da7..ee4e565 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -1467,3 +1467,51 @@
"没存到文件夹 ·" = "フォルダに未保存 ·";
"整理好后存到 %@" = "議事録ができたら %@ に保存";
"在访达中显示" = "Finder で表示";
+
+/* Voiceprint memory */
+"声纹库" = "声紋ライブラリ";
+"只保存在这台 Mac;删除后,以前的会议记录不会受影响。" = "このMacだけに保存されます。削除しても過去の会議記録は変わりません。";
+"还没有记住的人" = "まだ登録された人はいません";
+"在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。" = "会議で話者を開き「この声を記憶」を選ぶと、次回から自動で認識します。";
+"名字" = "名前";
+"%lld 段样本 · 最近 %@" = "%lld 件のサンプル · 最終 %@";
+"改名" = "名前を変更";
+"共 %lld 个人" = "%lld 人";
+"全部删除" = "すべて削除";
+"删除“%@”的声纹?" = "「%@」の声紋を削除しますか?";
+"之后的会议不会再自动认出这个人;已经生成的记录保持原样。" = "今後の会議ではこの人を自動認識しません。既存の記録は変わりません。";
+"删除全部声纹?" = "すべての声紋を削除しますか?";
+"之后所有会议都不会再自动认出人;已有记录保持原样。" = "今後の会議では誰も自動認識しなくなります。既存の記録は変わりません。";
+"还没在新会议里出现" = "新しい会議ではまだ検出されていません";
+"记住说话人" = "話者を記憶";
+"按本机声纹认出以前见过的人;不会上传声音" = "このMac上で声紋により以前会った人を認識します。音声はアップロードしません";
+"%lld 个人" = "%lld 人";
+"管理" = "管理";
+"声纹库:可能是 %@(%lld%%)" = "声紋ライブラリ:おそらく %@(%lld%%)";
+"声音像,但还不够确定。确认后,下次会议会直接认出。" = "声は似ていますが、まだ確実ではありません。確認すると次回から自動認識します。";
+"是 TA" = "はい、その人です";
+"不是" = "いいえ";
+"声纹库:%@" = "声紋ライブラリ:%@";
+"这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。" = "この会議はこの声紋でラベル付けされました。違う場合は今回の会議だけ解除できます。声紋は削除されません。";
+"更新声纹" = "声紋を更新";
+"记住这个声音" = "この声を記憶";
+"正在记住…" = "記憶しています…";
+"下次会议自动认出" = "次回は自動で認識";
+"需要 3 句以上发言;声纹只保存在这台 Mac" = "3文以上の発話が必要です。声紋はこのMacだけに保存されます";
+"先给这个人起个名字" = "先にこの人の名前を入力してください";
+"在“是谁”里输入名字后,再记住这个声音。" = "「誰」に名前を入力してから、この声を記憶してください。";
+"没有可用的录音" = "使用できる録音がありません";
+"打开“保存会议录音”,或用导入的录音文件建立声纹。" = "「会議音声を保存」をオンにするか、取り込んだ録音から声紋を作成してください。";
+"记住“%@”的声音?" = "「%@」の声を記憶しますか?";
+"声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。" = "声紋はこのMacだけに保存され、今後の会議でこの人を認識するために使います。声紋ライブラリからいつでも削除できます。";
+"记住" = "記憶";
+"不用" = "今はしない";
+"这个声音还不够清楚" = "この声は十分に明瞭ではありません";
+"换一段更长、更安静的发言再试。" = "もっと長く静かな発話で試してください。";
+"没记住这个声音" = "この声を記憶できませんでした";
+"这场会议没有可用的录音,先打开保存会议录音再试" = "この会議には使用できる録音がありません。先に「会議音声を保存」をオンにしてください。";
+"这个人的发言太少,至少要有 3 句、4 秒左右的声音" = "この人の発話が少なすぎます。3文以上、約4秒の音声が必要です。";
+"声纹模型加载失败,稍后再试" = "声紋モデルを読み込めませんでした。後でもう一度お試しください。";
+"已认出 %@" = "%@ を認識しました";
+"这次不再按声纹认人" = "この会議では声紋による認識を解除";
+"知道了" = "わかりました";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index d1c278e..700ec82 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -1467,3 +1467,51 @@
"没存到文件夹 ·" = "폴더에 저장 안 됨 ·";
"整理好后存到 %@" = "회의록이 준비되면 %@에 저장";
"在访达中显示" = "Finder에서 보기";
+
+/* Voiceprint memory */
+"声纹库" = "음성 지문 보관함";
+"只保存在这台 Mac;删除后,以前的会议记录不会受影响。" = "이 Mac에만 저장됩니다. 삭제해도 지난 회의 기록은 바뀌지 않습니다.";
+"还没有记住的人" = "아직 저장된 사람이 없습니다";
+"在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。" = "회의에서 발화자를 열고 '이 목소리 기억'을 선택하면 다음부터 자동으로 인식합니다.";
+"名字" = "이름";
+"%lld 段样本 · 最近 %@" = "%lld개 샘플 · 최근 %@";
+"改名" = "이름 변경";
+"共 %lld 个人" = "%lld명";
+"全部删除" = "모두 삭제";
+"删除“%@”的声纹?" = "“%@”의 음성 지문을 삭제할까요?";
+"之后的会议不会再自动认出这个人;已经生成的记录保持原样。" = "앞으로 이 사람을 자동으로 인식하지 않습니다. 기존 기록은 그대로 유지됩니다.";
+"删除全部声纹?" = "모든 음성 지문을 삭제할까요?";
+"之后所有会议都不会再自动认出人;已有记录保持原样。" = "앞으로 모든 회의에서 자동 인식을 중단합니다. 기존 기록은 그대로 유지됩니다.";
+"还没在新会议里出现" = "새 회의에서 아직 감지되지 않았습니다";
+"记住说话人" = "발화자 기억";
+"按本机声纹认出以前见过的人;不会上传声音" = "이 Mac에서 음성 지문으로 이전에 만난 사람을 인식합니다. 오디오는 업로드하지 않습니다";
+"%lld 个人" = "%lld명";
+"管理" = "관리";
+"声纹库:可能是 %@(%lld%%)" = "음성 지문 보관함: 아마 %@ (%lld%%)";
+"声音像,但还不够确定。确认后,下次会议会直接认出。" = "목소리가 비슷하지만 아직 확실하지 않습니다. 확인하면 다음 회의에서 바로 인식합니다.";
+"是 TA" = "네, 그 사람입니다";
+"不是" = "아니요";
+"声纹库:%@" = "음성 지문 보관함: %@";
+"这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。" = "이 회의는 이 음성 지문으로 표시되었습니다. 틀렸다면 이번 회의에서만 연결을 끊을 수 있으며 지문은 삭제되지 않습니다.";
+"更新声纹" = "음성 지문 업데이트";
+"记住这个声音" = "이 목소리 기억";
+"正在记住…" = "기억하는 중…";
+"下次会议自动认出" = "다음 회의에서 자동 인식";
+"需要 3 句以上发言;声纹只保存在这台 Mac" = "3문장 이상의 발언이 필요합니다. 음성 지문은 이 Mac에만 저장됩니다";
+"先给这个人起个名字" = "먼저 이 사람의 이름을 입력하세요";
+"在“是谁”里输入名字后,再记住这个声音。" = "'누구'에 이름을 입력한 뒤 이 목소리를 기억하세요.";
+"没有可用的录音" = "사용할 수 있는 녹음이 없습니다";
+"打开“保存会议录音”,或用导入的录音文件建立声纹。" = "'회의 오디오 저장'을 켜거나 가져온 녹음으로 음성 지문을 만드세요.";
+"记住“%@”的声音?" = "“%@”의 목소리를 기억할까요?";
+"声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。" = "음성 지문은 이 Mac에만 저장되며 앞으로 이 사람을 인식하는 데 사용됩니다. 음성 지문 보관함에서 언제든지 삭제할 수 있습니다.";
+"记住" = "기억";
+"不用" = "나중에";
+"这个声音还不够清楚" = "이 목소리가 충분히 선명하지 않습니다";
+"换一段更长、更安静的发言再试。" = "더 길고 조용한 발언으로 다시 시도하세요.";
+"没记住这个声音" = "이 목소리를 기억하지 못했습니다";
+"这场会议没有可用的录音,先打开保存会议录音再试" = "이 회의에는 사용할 수 있는 녹음이 없습니다. 먼저 '회의 오디오 저장'을 켜세요.";
+"这个人的发言太少,至少要有 3 句、4 秒左右的声音" = "이 사람의 발언이 너무 적습니다. 3문장 이상, 약 4초의 음성이 필요합니다.";
+"声纹模型加载失败,稍后再试" = "음성 지문 모델을 불러오지 못했습니다. 나중에 다시 시도하세요.";
+"已认出 %@" = "%@ 인식됨";
+"这次不再按声纹认人" = "이번 회의에서는 음성 지문 인식을 해제";
+"知道了" = "확인";
diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.strings
index e699782..e85e288 100644
--- a/Resources/zh-Hans.lproj/Localizable.strings
+++ b/Resources/zh-Hans.lproj/Localizable.strings
@@ -1375,3 +1375,51 @@
"没存到文件夹 ·" = "没存到文件夹 ·";
"整理好后存到 %@" = "整理好后存到 %@";
"在访达中显示" = "在访达中显示";
+
+/* Voiceprint memory */
+"声纹库" = "声纹库";
+"只保存在这台 Mac;删除后,以前的会议记录不会受影响。" = "只保存在这台 Mac;删除后,以前的会议记录不会受影响。";
+"还没有记住的人" = "还没有记住的人";
+"在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。" = "在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。";
+"名字" = "名字";
+"%lld 段样本 · 最近 %@" = "%lld 段样本 · 最近 %@";
+"改名" = "改名";
+"共 %lld 个人" = "共 %lld 个人";
+"全部删除" = "全部删除";
+"删除“%@”的声纹?" = "删除“%@”的声纹?";
+"之后的会议不会再自动认出这个人;已经生成的记录保持原样。" = "之后的会议不会再自动认出这个人;已经生成的记录保持原样。";
+"删除全部声纹?" = "删除全部声纹?";
+"之后所有会议都不会再自动认出人;已有记录保持原样。" = "之后所有会议都不会再自动认出人;已有记录保持原样。";
+"还没在新会议里出现" = "还没在新会议里出现";
+"记住说话人" = "记住说话人";
+"按本机声纹认出以前见过的人;不会上传声音" = "按本机声纹认出以前见过的人;不会上传声音";
+"%lld 个人" = "%lld 个人";
+"管理" = "管理";
+"声纹库:可能是 %@(%lld%%)" = "声纹库:可能是 %@(%lld%%)";
+"声音像,但还不够确定。确认后,下次会议会直接认出。" = "声音像,但还不够确定。确认后,下次会议会直接认出。";
+"是 TA" = "是 TA";
+"不是" = "不是";
+"声纹库:%@" = "声纹库:%@";
+"这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。" = "这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。";
+"更新声纹" = "更新声纹";
+"记住这个声音" = "记住这个声音";
+"正在记住…" = "正在记住…";
+"下次会议自动认出" = "下次会议自动认出";
+"需要 3 句以上发言;声纹只保存在这台 Mac" = "需要 3 句以上发言;声纹只保存在这台 Mac";
+"先给这个人起个名字" = "先给这个人起个名字";
+"在“是谁”里输入名字后,再记住这个声音。" = "在“是谁”里输入名字后,再记住这个声音。";
+"没有可用的录音" = "没有可用的录音";
+"打开“保存会议录音”,或用导入的录音文件建立声纹。" = "打开“保存会议录音”,或用导入的录音文件建立声纹。";
+"记住“%@”的声音?" = "记住“%@”的声音?";
+"声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。" = "声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。";
+"记住" = "记住";
+"不用" = "不用";
+"这个声音还不够清楚" = "这个声音还不够清楚";
+"换一段更长、更安静的发言再试。" = "换一段更长、更安静的发言再试。";
+"没记住这个声音" = "没记住这个声音";
+"这场会议没有可用的录音,先打开保存会议录音再试" = "这场会议没有可用的录音,先打开保存会议录音再试";
+"这个人的发言太少,至少要有 3 句、4 秒左右的声音" = "这个人的发言太少,至少要有 3 句、4 秒左右的声音";
+"声纹模型加载失败,稍后再试" = "声纹模型加载失败,稍后再试";
+"已认出 %@" = "已认出 %@";
+"这次不再按声纹认人" = "这次不再按声纹认人";
+"知道了" = "知道了";
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swift
index ed0d962..fa00246 100644
--- a/Sources/Cicada/AppModel.swift
+++ b/Sources/Cicada/AppModel.swift
@@ -165,15 +165,22 @@ final class AppModel: ObservableObject {
/// 存到文件夹 (settings › 通用).
lazy var folderExport = FolderExporter(store: store, settings: settings)
lazy var notesWindow = NotesWindowController(model: self)
- lazy var importer = FileImporter(store: store, settings: settings, translator: translator)
+ lazy var importer = FileImporter(store: store, settings: settings, translator: translator, profiles: profiles)
let vocabulary = Vocabulary(url: Vocabulary.defaultURL)
lazy var fixes = LiveFixes(store: store, vocabulary: vocabulary, settings: settings)
let sample = SamplePlayer()
let speakers = SpeakerTagger()
+ /// The local voiceprint library; never sent anywhere. See SpeakerProfiles.swift.
+ let profiles = SpeakerProfileStore()
+ /// A UI copy of `profiles`, refreshed by its onChange callback.
+ @Published private(set) var speakerProfiles: [SpeakerProfile] = []
+ @Published var speakerLibraryShown = false
+ @Published private(set) var speakerMemoryBusy = false
lazy var speakerNamer = SpeakerNamer(ling: ling, store: store)
/// The last speaker edit, offered as 撤销 at the bottom of both windows for a few seconds.
@Published var speakerUndo: SpeakerUndo?
private var speakerSetting: AnyCancellable?
+ private var speakerMemorySetting: AnyCancellable?
private var handsFreeSetting: AnyCancellable?
var openOnboarding: (() -> Void)?
@@ -237,6 +244,23 @@ final class AppModel: ObservableObject {
self.store.setVoice(lineID: line, voice)
if let id = self.store.liveID { self.speakerNamer.guess(id) }
}
+ speakerProfiles = profiles.all()
+ profiles.onChange = { [weak self] all in
+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.speakerProfiles = all } }
+ }
+ speakers.profiles = profiles
+ speakers.onProfile = { [weak self] line, voice, match in
+ guard let self, let id = self.store.liveID else { return }
+ self.store.setVoice(lineID: line, voice)
+ self.store.setVoiceProfile(id, voice: voice, ref: match.ref)
+ self.profiles.markSeen(id: match.profile.id)
+ self.speakerNamer.guess(id)
+ }
+ speakers.onSuggestion = { [weak self] line, voice, match in
+ guard let self, let id = self.store.liveID else { return }
+ self.store.setVoice(lineID: line, voice)
+ self.store.setVoiceSuggestion(id, voice: voice, match.ref)
+ }
// 不用按键 runs only while a meeting is being listened to: its lines are what tells the meeting's
// echo (`meetingSaid`), and the running unit mutes the built-in mic for other apps (#24), which
// then hear the virtual mic anyway. It pauses while 打开麦克风 is on: the room shares the unit and
@@ -257,6 +281,10 @@ final class AppModel: ObservableObject {
self?.listen.router.setVoiceCapture(on)
self?.roomListen.router.setVoiceCapture(on)
}
+ speakers.profiles = settings.speakerMemory ? profiles : nil
+ speakerMemorySetting = settings.$speakerMemory.sink { [weak self] on in
+ self?.speakers.profiles = on ? self?.profiles : nil
+ }
listen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }
roomListen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }
listen.onRefined = { [weak self] segID, text in self?.refined(segID, text) }
@@ -1373,7 +1401,7 @@ final class AppModel: ObservableObject {
/// Name a voice ("" keeps 说话人 N, nil goes back to Ling's guess).
func renameSpeaker(session id: String, voice: Int, _ name: String?) {
guard let s = store.session(id) else { return }
- let n = SpeakerLabels.voiceNumbers(s.lines)[voice] ?? 0
+ let n = SpeakerLabels.voiceNumbers(s)[voice] ?? 0
let before = SpeakerLabels.label(n, SpeakerLabels.names(s))
speakerEdit(id) { store.setVoiceName(id, voice: voice, name) }
let after = store.session(id).map { SpeakerLabels.label(n, SpeakerLabels.names($0)) } ?? before
@@ -1383,7 +1411,7 @@ final class AppModel: ObservableObject {
/// Two voices are one person. While listening the voiceprints merge too, which 撤销 can't take back.
func mergeSpeaker(session id: String, _ from: Int, into: Int) {
guard let s = store.session(id) else { return }
- let numbers = SpeakerLabels.voiceNumbers(s.lines), names = SpeakerLabels.names(s)
+ let numbers = SpeakerLabels.voiceNumbers(s), names = SpeakerLabels.names(s)
let a = SpeakerLabels.label(numbers[from] ?? 0, names), b = SpeakerLabels.label(numbers[into] ?? 0, names)
speakerEdit(id) { store.mergeVoice(id, from, into: into) }
if id == store.liveID { speakers.merge(from, into: into) }
@@ -1396,7 +1424,7 @@ final class AppModel: ObservableObject {
let first = s.lines.first { lines.contains($0.id) }
speakerEdit(id) { store.setLineVoices(id, lines: lines, voice) }
guard let s2 = store.session(id) else { return }
- let who = SpeakerLabels.label(SpeakerLabels.voiceNumbers(s2.lines)[voice] ?? 0, SpeakerLabels.names(s2))
+ let who = SpeakerLabels.label(SpeakerLabels.voiceNumbers(s2)[voice] ?? 0, SpeakerLabels.names(s2))
speakerUndo?.text = L("\(first.map { TranscriptExport.clock($0.t) } ?? "") 这句已改给 \(who)")
}
@@ -1418,6 +1446,116 @@ final class AppModel: ObservableObject {
}
}
+ // MARK: Voiceprint library
+
+ /// The user accepted a close match: name this meeting's voice from the library and let the
+ /// live clusterer use the profile for later lines.
+ func acceptSpeakerSuggestion(session id: String, voice: Int) {
+ guard let s = store.session(id), let ref = s.voiceSuggestions?[String(voice)],
+ let profile = profiles.snapshot().first(where: { $0.id == ref.id }) else { return }
+ speakerEdit(id) { store.setVoiceProfile(id, voice: voice, ref: ref) }
+ profiles.markSeen(id: profile.id)
+ if id == store.liveID { speakers.bind(voice: voice, profile: profile) }
+ speakerUndo?.text = L("已认出 \(ref.name)")
+ }
+
+ func dismissSpeakerSuggestion(session id: String, voice: Int) {
+ store.setVoiceSuggestion(id, voice: voice, nil)
+ }
+
+ /// "不是 TA": drop this meeting's binding; never touch the global profile.
+ func forgetSpeaker(session id: String, voice: Int) {
+ guard store.session(id)?.voiceProfiles?[String(voice)] != nil else { return }
+ speakerEdit(id) { store.setVoiceProfile(id, voice: voice, ref: nil) }
+ speakerUndo?.text = L("这次不再按声纹认人")
+ }
+
+ /// Explicit enrolment: the caller has already named the voice. The alert is the consent step;
+ /// voiceprints are biometric data and are never saved from a background match alone.
+ func rememberSpeaker(session id: String, voice: Int, name: String? = nil) {
+ guard let s = store.session(id) else { return }
+ let n = SpeakerLabels.voiceNumbers(s)[voice] ?? 0
+ let chosen = (name ?? s.voiceNames?[String(voice)] ?? s.voiceProfiles?[String(voice)]?.name
+ ?? SpeakerLabels.names(s)[n] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !chosen.isEmpty else {
+ alert(L("先给这个人起个名字"), L("在“是谁”里输入名字后,再记住这个声音。"))
+ return
+ }
+ guard let audio = audioURL(for: s) else {
+ alert(L("没有可用的录音"), L("打开“保存会议录音”,或用导入的录音文件建立声纹。"))
+ return
+ }
+ let alert = NSAlert()
+ alert.messageText = L("记住“\(chosen)”的声音?")
+ alert.informativeText = L("声纹只保存在这台 Mac,用于以后会议自动认出这个人;可以随时在声纹库里删除。")
+ alert.addButton(withTitle: L("记住"))
+ alert.addButton(withTitle: L("不用"))
+ guard alert.runModal() == .alertFirstButtonReturn else { return }
+
+ speakerMemoryBusy = true
+ Task { [weak self] in
+ guard let self else { return }
+ defer { self.speakerMemoryBusy = false }
+ do {
+ let result = try await SpeakerEnrollment.build(session: s, voice: voice, audioURL: audio)
+ let existing = s.voiceProfiles?[String(voice)]?.id
+ let profile: SpeakerProfile?
+ if let existing, self.profiles.updateEmbedding(id: existing, embedding: result.embedding) {
+ _ = self.profiles.rename(id: existing, to: chosen)
+ profile = self.profiles.snapshot().first { $0.id == existing }
+ } else {
+ profile = self.profiles.remember(name: chosen, embedding: result.embedding)
+ }
+ guard let profile else {
+ self.alert(L("这个声音还不够清楚"), L("换一段更长、更安静的发言再试。"))
+ return
+ }
+ self.store.setVoiceProfile(id, voice: voice, ref: VoiceProfileRef(id: profile.id, name: profile.name, similarity: 1))
+ self.profiles.markSeen(id: profile.id)
+ if id == self.store.liveID, let full = self.profiles.snapshot().first(where: { $0.id == profile.id }) {
+ self.speakers.bind(voice: voice, profile: full)
+ }
+ self.speakerProfiles = self.profiles.all()
+ debugLog("voice profiles: remembered \(chosen) from \(result.clips) clips / \(Int(result.seconds)) s")
+ } catch {
+ self.alert(L("没记住这个声音"), error.localizedDescription)
+ }
+ }
+ }
+
+ func renameSpeakerProfile(id: UUID, to name: String) {
+ guard profiles.rename(id: id, to: name) else { return }
+ speakerProfiles = profiles.all()
+ }
+
+ func deleteSpeakerProfile(id: UUID) {
+ profiles.delete(id: id)
+ speakerProfiles = profiles.all()
+ }
+
+ func deleteAllSpeakerProfiles() {
+ profiles.deleteAll()
+ speakerProfiles = profiles.all()
+ }
+
+ func speakerSuggestion(session id: String, voice: Int) -> VoiceProfileRef? {
+ store.session(id)?.voiceSuggestions?[String(voice)]
+ }
+
+ private func audioURL(for s: Session) -> URL? {
+ if let path = s.sourcePath, s.sourceFile != nil { return URL(fileURLWithPath: path) }
+ let system = store.systemAudioURL(s.id)
+ return FileManager.default.fileExists(atPath: system.path) ? system : nil
+ }
+
+ private func alert(_ title: String, _ message: String) {
+ let a = NSAlert()
+ a.messageText = title
+ a.informativeText = message
+ a.addButton(withTitle: L("知道了"))
+ a.runModal()
+ }
+
// MARK: 电脑和会议室
private func startRoomSide() {
@@ -1594,17 +1732,18 @@ final class AppModel: ObservableObject {
// Two voices never share a line: hear whose this is first (a few hundredths of a second).
if settings.speakerVoices, let samples = seg.voiceSamples, seg.text.filter(\.isLetter).count >= 2 {
heldJoin = (seg, t, nil)
- speakers.voice(of: samples) { [weak self] voice in self?.heardVoice(seg, voice) }
+ speakers.voice(of: samples) { [weak self] assignment in self?.heardVoice(seg, assignment) }
return
}
join(seg, onto: prev)
}
- private func heardVoice(_ seg: Segment, _ voice: Int?) {
+ private func heardVoice(_ seg: Segment, _ assignment: SpeakerAssignment) {
+ let voice = assignment.voice
guard let held = heldJoin, held.seg.id == seg.id else {
// Already recorded on its own (another line came first).
if let line = lineForSegment[seg.id] {
- if let voice { speakers.onVoice?(line, voice) }
+ apply(assignment, to: line)
voicePending.remove(line)
}
return
@@ -1616,7 +1755,22 @@ final class AppModel: ObservableObject {
join(seg, onto: prev) // the earlier line's voice stays
} else {
appendHeard(seg, t: held.t, translation: held.translation)
- if let voice, let line = lineForSegment[seg.id] { speakers.onVoice?(line, voice) }
+ if let line = lineForSegment[seg.id] { apply(assignment, to: line) }
+ }
+ }
+
+ /// Put a voice (and a library match, if any) on a recorded line. Used when a line was held
+ /// back for its voice instead of going through `SpeakerTagger.tag`.
+ private func apply(_ assignment: SpeakerAssignment, to line: String) {
+ guard let voice = assignment.voice else { return }
+ speakers.onVoice?(line, voice)
+ guard let match = assignment.match, let id = store.liveID else { return }
+ store.setVoice(lineID: line, voice)
+ if match.kind == .auto {
+ store.setVoiceProfile(id, voice: voice, ref: match.ref)
+ profiles.markSeen(id: match.profile.id)
+ } else {
+ store.setVoiceSuggestion(id, voice: voice, match.ref)
}
}
diff --git a/Sources/Cicada/FileImport.swift b/Sources/Cicada/FileImport.swift
index da46526..35dce7f 100644
--- a/Sources/Cicada/FileImport.swift
+++ b/Sources/Cicada/FileImport.swift
@@ -41,14 +41,16 @@ final class FileImporter: ObservableObject {
let store: SessionStore
let settings: AppSettings
let translator: TranslationService
+ let profiles: SpeakerProfileStore
private var task: Task<Void, Never>?
/// The running `SpeechAnalyzer` (macOS 26) or `RecognitionStream`, for 停止转写.
private var analyzer: AnyObject?
- init(store: SessionStore, settings: AppSettings, translator: TranslationService) {
+ init(store: SessionStore, settings: AppSettings, translator: TranslationService, profiles: SpeakerProfileStore) {
self.store = store
self.settings = settings
self.translator = translator
+ self.profiles = profiles
}
var busy: Bool { current != nil }
@@ -180,7 +182,7 @@ final class FileImporter: ObservableObject {
var n = 0
var translations: [Task<Void, Never>] = []
// 说话人识别, as when listening: each line's stretch of the file gets a voiceprint.
- let voices = settings.speakerVoices ? ImportVoices(pcm: pcm, store: store, session: job.id) : nil
+ let voices = settings.speakerVoices ? ImportVoices(pcm: pcm, store: store, session: job.id, profiles: profiles) : nil
defer { voices?.stop() }
// `end`: when the recognized stretch ends, so its last line's sound ends there.
let add = { (sentences: [(text: String, t: Double)], end: Double, heard: String?, translation: String?) in
@@ -436,12 +438,23 @@ final class ImportVoices {
/// a 重新转写 that reuses the line ids.
private var on = true
- init(pcm: URL, store: SessionStore, session id: String) {
+ init(pcm: URL, store: SessionStore, session id: String, profiles: SpeakerProfileStore) {
file = try? AVAudioFile(forReading: pcm)
+ tagger.profiles = profiles
tagger.onVoice = { [weak self, weak store] line, voice in
guard self?.on == true else { return }
store?.setVoice(in: id, lineID: line, voice)
}
+ tagger.onProfile = { [weak self, weak store] line, voice, match in
+ guard self?.on == true else { return }
+ store?.setVoice(in: id, lineID: line, voice)
+ store?.setVoiceProfile(id, voice: voice, ref: match.ref)
+ }
+ tagger.onSuggestion = { [weak self, weak store] line, voice, match in
+ guard self?.on == true else { return }
+ store?.setVoice(in: id, lineID: line, voice)
+ store?.setVoiceSuggestion(id, voice: voice, match.ref)
+ }
}
func tag(_ lineID: String, from start: Double, to end: Double) {
diff --git a/Sources/Cicada/Notes.swift b/Sources/Cicada/Notes.swift
index 022a4b6..d56e57b 100644
--- a/Sources/Cicada/Notes.swift
+++ b/Sources/Cicada/Notes.swift
@@ -293,17 +293,18 @@ final class NotesEngine: ObservableObject {
let from = final ? 0 : min(base.covered, lines.count)
let lang = language(id)
let names = TranscriptExport.voices ? SpeakerLabels.names(session) : [:]
+ let known = SpeakerLabels.knownVoices(session)
// A live update returns only the last topics: when it rewrote them all, its reply grew with
// 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.
let frozen = final || fresh ? 0 : max(0, base.topics.count - Self.editableTopics)
- let prompt = Self.prompt(notes: base, lines: lines, from: from, language: lang, final: final, names: names, frozen: frozen)
+ let prompt = Self.prompt(notes: base, lines: lines, from: from, language: lang, final: final, names: names, frozen: frozen, known: known)
let started = Date()
do {
// The final pass sends only the transcript, with no notes in the reader's language to
// follow: given a long English meeting the model drifts into English. Say the language
// again where it is read last, and try once more if the reply still isn't in it.
- var next = final ? await longFinal(lines, names: names, language: lang, startedAt: session.lines.first?.t ?? 0) : nil
+ var next = final ? await longFinal(lines, names: names, known: known, language: lang, startedAt: session.lines.first?.t ?? 0) : nil
for attempt in 1...(final || fresh ? 2 : 1) where next == nil {
let raw = try await ling.chat(content: prompt, instruction: "Update the notes. Write them in \(lang).",
priority: .notes, json: true, maxTokens: 6000, timeout: 90, patient: final)
@@ -356,7 +357,7 @@ final class NotesEngine: ObservableObject {
/// A long meeting's final pass: each part noted on its own, all at once, then merged into one.
/// nil when a step fails: the caller then makes one pass over the whole transcript, as before.
- private func longFinal(_ lines: [TranscriptLine], names: [Int: String], language lang: String,
+ private func longFinal(_ lines: [TranscriptLine], names: [Int: String], known: Set<Int>, language lang: String,
startedAt: Double) async -> MeetingNotes? {
let parts = Self.parts(lines)
guard parts.count > 1 else { return nil }
@@ -366,7 +367,7 @@ final class NotesEngine: ObservableObject {
await withTaskGroup(of: (Int, String?).self) { group in
for (i, range) in parts.enumerated() {
let prompt = Self.prompt(notes: MeetingNotes(), lines: Array(lines.prefix(range.upperBound)), from: range.lowerBound,
- language: lang, final: true, names: names, part: (i + 1, parts.count))
+ language: lang, final: true, names: names, part: (i + 1, parts.count), known: known)
group.addTask { [ling] in
let raw = try? await ling.chat(content: prompt, instruction: "Write the notes for this part. Write them in \(lang).",
priority: .notes, json: true, maxTokens: 6000, timeout: 90)
@@ -513,8 +514,9 @@ final class NotesEngine: ObservableObject {
/// `part`: in a long meeting's final pass, which part `from..<lines.count` is (1-based, of `of`).
static func prompt(notes: MeetingNotes, lines: [TranscriptLine], from: Int, language: String, final: Bool,
- names: [Int: String] = [:], frozen: Int = 0, part: (index: Int, of: Int)? = nil) -> String {
- let numbers = TranscriptExport.voices ? SpeakerLabels.numbers(lines) : [:]
+ names: [Int: String] = [:], frozen: Int = 0, part: (index: Int, of: Int)? = nil,
+ known: Set<Int> = []) -> String {
+ let numbers = TranscriptExport.voices ? SpeakerLabels.numbers(lines, known: known) : [:]
func line(_ i: Int) -> String {
let l = lines[i]
// A named voice goes as its name: notes then say "George" rather than "说话人2".
diff --git a/Sources/Cicada/NotesWindow.swift b/Sources/Cicada/NotesWindow.swift
index 549a840..dcf2d0b 100644
--- a/Sources/Cicada/NotesWindow.swift
+++ b/Sources/Cicada/NotesWindow.swift
@@ -903,7 +903,7 @@ struct NotesWindowView: View {
private var transcript: some View {
let ms = matches
let lines = session?.lines ?? []
- let speakers = model.settings.speakerVoices ? SpeakerLabels.numbers(lines) : [:]
+ let speakers = model.settings.speakerVoices ? session.map(SpeakerLabels.numbers) ?? [:] : [:]
return VStack(alignment: .leading, spacing: 10) {
if !speakers.isEmpty, let s = session {
SpeakerStrip(model: model, session: s, editing: $editingVoice)
@@ -913,7 +913,7 @@ struct NotesWindowView: View {
partialShown: TranscriptPartial.shows(model.liveSource, live: live, after: lines.last?.src),
jumpTo: jumpTo, speakers: speakers, startedAt: store.liveStart,
identifying: model.identifyingLanguage,
- voices: speakers.isEmpty ? [:] : SpeakerLabels.voiceNumbers(lines), marked: editingVoice,
+ voices: speakers.isEmpty ? [:] : session.map(SpeakerLabels.voiceNumbers) ?? [:], marked: editingVoice,
places: RecordList.heardBoth(lines), settling: model.settling, voicePending: model.voicePending,
onAssign: { ids, voice in if let s = session { model.assignLines(session: s.id, ids, to: voice) } },
onRevert: { lineID, fix in if let s = session { model.fixes.revert(fix, lineID: lineID, in: s.id) } }) {
diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swift
index 6496c4e..8864043 100644
--- a/Sources/Cicada/SessionStore.swift
+++ b/Sources/Cicada/SessionStore.swift
@@ -43,6 +43,11 @@ struct Session: Codable, Identifiable, Equatable {
var voiceNames: [String: String]? = nil
/// Names Ling read from the conversation, keyed by voice id; shown until the user says otherwise.
var voiceGuesses: [String: VoiceGuess]? = nil
+ /// A voice this meeting matched to the local voiceprint library, keyed by voice id. The name
+ /// is a snapshot: deleting the profile later must not make an old record unreadable.
+ var voiceProfiles: [String: VoiceProfileRef]? = nil
+ /// Similar matches waiting for the user to say yes. Suggestions are never shown as the name.
+ var voiceSuggestions: [String: VoiceProfileRef]? = nil
/// An imported recording or video: its file name, where it was (played from there; never
/// copied or deleted), and true until transcribing it finished.
var sourceFile: String? = nil
@@ -270,13 +275,16 @@ final class SessionStore: ObservableObject {
let voices: [String: Int?]
let names: [String: String]?
let guesses: [String: VoiceGuess]?
+ let profiles: [String: VoiceProfileRef]?
+ let suggestions: [String: VoiceProfileRef]?
}
func voiceSnapshot(_ id: String) -> VoiceSnapshot? {
guard let s = session(id) else { return nil }
var voices: [String: Int?] = [:]
for l in s.lines { voices[l.id] = .some(l.voice) }
- return VoiceSnapshot(voices: voices, names: s.voiceNames, guesses: s.voiceGuesses)
+ return VoiceSnapshot(voices: voices, names: s.voiceNames, guesses: s.voiceGuesses,
+ profiles: s.voiceProfiles, suggestions: s.voiceSuggestions)
}
func restore(_ id: String, _ snap: VoiceSnapshot) {
@@ -287,6 +295,8 @@ final class SessionStore: ObservableObject {
}
sessions[i].voiceNames = snap.names
sessions[i].voiceGuesses = snap.guesses
+ sessions[i].voiceProfiles = snap.profiles
+ sessions[i].voiceSuggestions = snap.suggestions
saveNow(id)
}
@@ -299,6 +309,28 @@ final class SessionStore: ObservableObject {
saveNow(id)
}
+ /// A voice was recognised by the local voiceprint library. The suggestion, if any, is spent.
+ func setVoiceProfile(_ id: String, voice: Int, ref: VoiceProfileRef?) {
+ guard let i = index(id) else { return }
+ var profiles = sessions[i].voiceProfiles ?? [:]
+ profiles[String(voice)] = ref
+ sessions[i].voiceProfiles = profiles.isEmpty ? nil : profiles
+ if var suggestions = sessions[i].voiceSuggestions {
+ suggestions[String(voice)] = nil
+ sessions[i].voiceSuggestions = suggestions.isEmpty ? nil : suggestions
+ }
+ saveNow(id)
+ }
+
+ /// A close voiceprint match waiting for the user. Never used as the displayed name by itself.
+ func setVoiceSuggestion(_ id: String, voice: Int, _ ref: VoiceProfileRef?) {
+ guard let i = index(id) else { return }
+ var suggestions = sessions[i].voiceSuggestions ?? [:]
+ suggestions[String(voice)] = ref
+ sessions[i].voiceSuggestions = suggestions.isEmpty ? nil : suggestions
+ saveNow(id)
+ }
+
/// Ling's latest guesses; 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.
func setVoiceGuesses(_ id: String, _ guesses: [Int: VoiceGuess], refuted: [Int: String] = [:]) {
@@ -324,6 +356,14 @@ final class SessionStore: ObservableObject {
if guesses[String(into)] == nil { guesses[String(into)] = moved }
sessions[i].voiceGuesses = guesses.isEmpty ? nil : guesses
}
+ if var profiles = sessions[i].voiceProfiles, let moved = profiles.removeValue(forKey: String(from)) {
+ if profiles[String(into)] == nil { profiles[String(into)] = moved }
+ sessions[i].voiceProfiles = profiles.isEmpty ? nil : profiles
+ }
+ if var suggestions = sessions[i].voiceSuggestions {
+ suggestions[String(from)] = nil
+ sessions[i].voiceSuggestions = suggestions.isEmpty ? nil : suggestions
+ }
saveNow(id)
}
@@ -359,6 +399,8 @@ final class SessionStore: ObservableObject {
// Voices are numbered afresh: names given to the old ones would land on other people.
sessions[i].voiceNames = nil
sessions[i].voiceGuesses = nil
+ sessions[i].voiceProfiles = nil
+ sessions[i].voiceSuggestions = nil
sessions[i].importing = true
saveNow(id)
}
@@ -470,7 +512,7 @@ enum TranscriptExport {
return numbers.isEmpty ? L("对方") : L("未识别")
}
- static func speakerNumbers(_ s: Session) -> [String: Int] { voices ? SpeakerLabels.numbers(s.lines) : [:] }
+ static func speakerNumbers(_ s: Session) -> [String: Int] { voices ? SpeakerLabels.numbers(s) : [:] }
/// Whether lines say who spoke. An imported file has no "other side" to call 对方: its lines
/// are named only once its voices are told apart.
diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swift
index 232bd88..7e709fe 100644
--- a/Sources/Cicada/Settings.swift
+++ b/Sources/Cicada/Settings.swift
@@ -229,6 +229,12 @@ final class AppSettings: ObservableObject {
didSet { save() }
}
+ /// Recognise people saved in the local voiceprint library. Enrolling a voice is always an
+ /// explicit action with its own consent alert; this switch only controls automatic naming.
+ @Published var speakerMemory: Bool {
+ didSet { save() }
+ }
+
/// 会中改正听错的词: finished sentences carry the word list to the AI service, which points out
/// misheard words (`Correction`). On by default; does nothing without an AI service.
@Published var fixMisheard: Bool {
@@ -326,6 +332,7 @@ final class AppSettings: ObservableObject {
defaults.set(true, forKey: "speakerVoices")
defaults.set(true, forKey: "speakerVoicesRegular")
}
+ speakerMemory = defaults.object(forKey: "speakerMemory") as? Bool ?? true
}
private func save() {
@@ -378,6 +385,7 @@ final class AppSettings: ObservableObject {
defaults.set(diagnostics, forKey: "diagnostics")
defaults.set(notesCapturable, forKey: "notesCapturable")
defaults.set(speakerVoices, forKey: "speakerVoices")
+ defaults.set(speakerMemory, forKey: "speakerMemory")
defaults.set(fixMisheard, forKey: "fixMisheard")
defaults.set(askNames, forKey: "askNames")
}
diff --git a/Sources/Cicada/SettingsWindow.swift b/Sources/Cicada/SettingsWindow.swift
index 35c7f52..b562a1b 100644
--- a/Sources/Cicada/SettingsWindow.swift
+++ b/Sources/Cicada/SettingsWindow.swift
@@ -735,6 +735,13 @@ struct SettingsView: View {
Toggle("说话人识别", isOn: $settings.speakerVoices)
.toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)
}
+ SettingsRow(title: L("记住说话人"), detail: L("按本机声纹认出以前见过的人;不会上传声音")) {
+ Toggle("记住说话人", isOn: $settings.speakerMemory)
+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)
+ }
+ SettingsRow(title: L("声纹库"), detail: L("\(model.speakerProfiles.count) 个人")) {
+ SoftButton(L("管理")) { model.speakerLibraryShown = true }
+ }
SettingsRow(title: L("记录文件夹"), divider: false) {
SoftButton(L("打开")) { NSWorkspace.shared.open(model.store.root) }
}
@@ -776,5 +783,8 @@ struct SettingsView: View {
}
AppRows(updates: model.updates, loginItem: model.loginItem, model: model)
}
+ .sheet(isPresented: $model.speakerLibraryShown) {
+ SpeakerLibraryView(model: model)
+ }
}
}
diff --git a/Sources/Cicada/ShareProjection.swift b/Sources/Cicada/ShareProjection.swift
index 2e6c10a..0956f17 100644
--- a/Sources/Cicada/ShareProjection.swift
+++ b/Sources/Cicada/ShareProjection.swift
@@ -53,7 +53,7 @@ enum ShareScope: String, CaseIterable {
enum ShareProjection {
/// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.
static func doc(_ s: Session, scope: ShareScope, names: Bool, removed: Set<Int> = [], dropNotes: Bool = false) -> ShareDoc {
- let numbers = SpeakerLabels.numbers(s.lines)
+ let numbers = SpeakerLabels.numbers(s)
let nameMap = names ? SpeakerLabels.names(s) : [:]
func who(_ l: TranscriptLine) -> String {
if l.speaker == "me" { return L("分享者") }
diff --git a/Sources/Cicada/SpeakerEnrollment.swift b/Sources/Cicada/SpeakerEnrollment.swift
new file mode 100644
index 0000000..d02947a
--- /dev/null
+++ b/Sources/Cicada/SpeakerEnrollment.swift
@@ -0,0 +1,99 @@
+import AVFoundation
+import Foundation
+
+/// Turns the recorded stretches of one local voice in a meeting into a profile embedding. This is
+/// deliberately separate from the live clusterer: it also works after the app restarted, for an old
+/// record the user wants to add to the library.
+enum SpeakerEnrollmentError: LocalizedError {
+ case noAudio
+ case notEnoughSpeech
+ case modelUnavailable
+
+ var errorDescription: String? {
+ switch self {
+ case .noAudio: L("这场会议没有可用的录音,先打开保存会议录音再试")
+ case .notEnoughSpeech: L("这个人的发言太少,至少要有 3 句、4 秒左右的声音")
+ case .modelUnavailable: L("声纹模型加载失败,稍后再试")
+ }
+ }
+}
+
+struct SpeakerEnrollmentResult {
+ var embedding: [Float]
+ var clips: Int
+ var seconds: Double
+}
+
+enum SpeakerEnrollment {
+ static let minimumClips = 3
+ static let minimumSeconds = 4.0
+ private static let maximumClipSeconds = 12.0
+
+ /// `audioURL`: the meeting's system recording, or an imported file's source.
+ static func build(session: Session, voice: Int, audioURL: URL,
+ packageURL: URL? = nil) async throws -> SpeakerEnrollmentResult {
+ try await Task.detached(priority: .utility) {
+ try buildSync(session: session, voice: voice, audioURL: audioURL, packageURL: packageURL)
+ }.value
+ }
+
+ private static func buildSync(session: Session, voice: Int, audioURL: URL,
+ packageURL: URL?) throws -> SpeakerEnrollmentResult {
+ guard let file = try? AVAudioFile(forReading: audioURL) else { throw SpeakerEnrollmentError.noAudio }
+ let candidates = session.lines.enumerated().filter { _, line in
+ line.speaker == "them" && line.voice == voice && SpeakerLabels.substantive(line.src)
+ }
+ guard !candidates.isEmpty else { throw SpeakerEnrollmentError.notEnoughSpeech }
+
+ let model: Voiceprints
+ do { model = try Voiceprints.load(packageURL: packageURL) } catch { throw SpeakerEnrollmentError.modelUnavailable }
+
+ var embeddings: [[Float]] = []
+ var seconds = 0.0
+ for (index, line) in candidates {
+ let next = session.lines.indices.contains(index + 1) ? session.lines[index + 1].t : session.duration
+ let end = min(next, line.t + maximumClipSeconds)
+ guard end - line.t >= 0.5, let samples = read(file, from: line.t, to: end),
+ let embedding = model.embed(samples) else { continue }
+ embeddings.append(embedding)
+ seconds += Double(samples.count) / 16_000
+ }
+ guard embeddings.count >= minimumClips, seconds >= minimumSeconds,
+ let mean = SpeakerEmbedding.mean(embeddings) else { throw SpeakerEnrollmentError.notEnoughSpeech }
+ return SpeakerEnrollmentResult(embedding: mean, clips: embeddings.count, seconds: seconds)
+ }
+
+ /// 16 kHz mono floats from `start` to `end` seconds, converting the file's rate and channels.
+ /// `ImportVoices.read` is only for files already decoded to 16 kHz; meeting .m4a files are not.
+ private static func read(_ file: AVAudioFile, from start: Double, to end: Double) -> [Float]? {
+ let rate = file.processingFormat.sampleRate
+ let first = AVAudioFramePosition(max(0, start) * rate)
+ let last = min(file.length, AVAudioFramePosition(max(0, end) * rate))
+ guard last > first, let input = AVAudioPCMBuffer(pcmFormat: file.processingFormat,
+ frameCapacity: AVAudioFrameCount(last - first)) else { return nil }
+ file.framePosition = first
+ var frames: AVAudioFrameCount = 0
+ while file.framePosition < last {
+ let want = AVAudioFrameCount(last - file.framePosition)
+ guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: want),
+ (try? file.read(into: buf, frameCount: want)) != nil, buf.frameLength > 0 else { break }
+ input.frameLength = frames + buf.frameLength
+ // AVAudioPCMBuffer has no append API: copy into the backing float channels.
+ if let src = buf.floatChannelData, let dst = input.floatChannelData {
+ for ch in 0..<Int(file.processingFormat.channelCount) {
+ dst[ch].advanced(by: Int(frames)).update(from: src[ch], count: Int(buf.frameLength))
+ }
+ } else {
+ return nil
+ }
+ frames += buf.frameLength
+ }
+ guard frames > 0 else { return nil }
+ input.frameLength = frames
+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000,
+ channels: 1, interleaved: false)!
+ guard let converted = PCMConverter().convert(input, to: format),
+ let data = converted.floatChannelData else { return nil }
+ return Array(UnsafeBufferPointer(start: data[0], count: Int(converted.frameLength)))
+ }
+}
diff --git a/Sources/Cicada/SpeakerID.swift b/Sources/Cicada/SpeakerID.swift
index 8425dce..89fd9b6 100644
--- a/Sources/Cicada/SpeakerID.swift
+++ b/Sources/Cicada/SpeakerID.swift
@@ -92,14 +92,15 @@ final class Voiceprints: @unchecked Sendable {
private init(model: MLModel) { self.model = model }
- static func load() throws -> Voiceprints {
- guard let pkg = Bundle.main.url(forResource: "SpeakerEmbedding", withExtension: "mlpackage") else {
+ static func load(packageURL: URL? = nil) throws -> Voiceprints {
+ guard let pkg = packageURL ?? Bundle.main.url(forResource: "SpeakerEmbedding", withExtension: "mlpackage") else {
throw CocoaError(.fileNoSuchFile)
}
let size = (try? FileManager.default.attributesOfItem(atPath: pkg.appendingPathComponent("Data/com.apple.CoreML/weights/weight.bin").path)[.size] as? Int) ?? 0
let cache = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("SpeakerEmbedding-\(size).mlmodelc")
if !FileManager.default.fileExists(atPath: cache.path) {
+ try? FileManager.default.createDirectory(at: cache.deletingLastPathComponent(), withIntermediateDirectories: true)
let compiled = try MLModel.compileModel(at: pkg)
try? FileManager.default.removeItem(at: cache)
try FileManager.default.moveItem(at: compiled, to: cache)
@@ -161,6 +162,39 @@ struct VoiceClusterer {
private(set) var sums: [[Float]] = []
+ /// A unit-length centroid for a voice, for saving it to the profile library.
+ func centroid(_ voice: Int) -> [Float]? {
+ guard sums.indices.contains(voice) else { return nil }
+ return SpeakerEmbedding.normalized(sums[voice])
+ }
+
+ /// The voice closest to `embedding`, when it is at least `minimum` similar.
+ func closest(to embedding: [Float], minimum: Float) -> Int? {
+ guard let probe = SpeakerEmbedding.normalized(embedding) else { return nil }
+ var best: Int?
+ var bestScore = minimum
+ for i in sums.indices {
+ guard let c = centroid(i), let score = SpeakerEmbedding.cosine(probe, c) else { continue }
+ if score >= bestScore { best = i; bestScore = score }
+ }
+ return best
+ }
+
+ /// Start a voice from a known profile's centroid. The next lines join it by the ordinary
+ /// 0.5 within-meeting threshold, while the profile id stays at the session level.
+ mutating func seed(_ embedding: [Float]) -> Int? {
+ guard let v = SpeakerEmbedding.normalized(embedding) else { return nil }
+ sums.append(v)
+ return sums.count - 1
+ }
+
+ /// Add a profile centroid to an existing voice after the user confirms a suggestion, so later
+ /// lines of that person keep joining it more readily.
+ mutating func adopt(_ embedding: [Float], into voice: Int) {
+ guard sums.indices.contains(voice), let v = SpeakerEmbedding.normalized(embedding) else { return }
+ vDSP_vadd(sums[voice], 1, v, 1, &sums[voice], 1, vDSP_Length(sums[voice].count))
+ }
+
/// The user said two voices are one: later lines like either go to `into`.
mutating func merge(_ from: Int, into: Int) {
guard sums.indices.contains(from), sums.indices.contains(into), from != into else { return }
@@ -203,22 +237,40 @@ enum SpeakerLabels {
return text.unicodeScalars.filter { $0.properties.isIdeographic || (0x3040...0x30FF).contains($0.value) || (0xAC00...0xD7A3).contains($0.value) }.count >= 4
}
- /// Voice id → 1-based speaker number, for the voices on show.
- static func voiceNumbers(_ lines: [TranscriptLine]) -> [Int: Int] {
+ /// Voice id → 1-based speaker number, for the voices on show. `known`: voices remembered by
+ /// the local voiceprint library; they get a number (and a name) before the five-line rule, so a
+ /// returning customer is named from their first sentence. A single known voice may be shown
+ /// on its own, unlike an anonymous one (a one-to-one call otherwise stays "对方").
+ static func voiceNumbers(_ lines: [TranscriptLine], known: Set<Int> = []) -> [Int: Int] {
var count: [Int: Int] = [:], reached: [Int: Int] = [:]
for (i, l) in lines.enumerated() where l.speaker == "them" {
guard let v = l.voice, substantive(l.src) else { continue }
count[v, default: 0] += 1
- if count[v] == shownAfter { reached[v] = i }
+ if reached[v] == nil {
+ if known.contains(v) {
+ reached[v] = i
+ } else if count[v] == shownAfter {
+ reached[v] = i
+ }
+ }
}
let shown = reached.keys.sorted { reached[$0]! < reached[$1]! }
- guard shown.count >= 2 else { return [:] }
+ guard shown.count >= 2 || !known.isEmpty else { return [:] }
return Dictionary(uniqueKeysWithValues: shown.enumerated().map { ($1, $0 + 1) })
}
+ /// The voices a meeting already knows by name; `Session.voiceProfiles` is the snapshot.
+ static func knownVoices(_ s: Session) -> Set<Int> {
+ Set((s.voiceProfiles ?? [:]).keys.compactMap(Int.init))
+ }
+
+ static func voiceNumbers(_ s: Session) -> [Int: Int] {
+ voiceNumbers(s.lines, known: knownVoices(s))
+ }
+
/// Line id → 1-based speaker number; lines without one show as 对方.
- static func numbers(_ lines: [TranscriptLine]) -> [String: Int] {
- let number = voiceNumbers(lines)
+ static func numbers(_ lines: [TranscriptLine], known: Set<Int> = []) -> [String: Int] {
+ let number = voiceNumbers(lines, known: known)
var out: [String: Int] = [:]
for l in lines where l.speaker == "them" {
if let v = l.voice, let n = number[v] { out[l.id] = n }
@@ -226,13 +278,20 @@ enum SpeakerLabels {
return out
}
- /// Speaker number → name: the user's, else Ling's guess (unless the user turned it down).
+ static func numbers(_ s: Session) -> [String: Int] {
+ numbers(s.lines, known: knownVoices(s))
+ }
+
+ /// Speaker number → name: the user's, else the local voiceprint name, else Ling's guess.
static func names(_ s: Session) -> [Int: String] {
- guard s.voiceNames != nil || s.voiceGuesses != nil else { return [:] }
+ let known = knownVoices(s)
+ guard s.voiceNames != nil || s.voiceGuesses != nil || !known.isEmpty else { return [:] }
var out: [Int: String] = [:]
- for (v, n) in voiceNumbers(s.lines) {
+ for (v, n) in voiceNumbers(s.lines, known: known) {
if let mine = s.voiceNames?[String(v)] {
if !mine.isEmpty { out[n] = mine }
+ } else if let p = s.voiceProfiles?[String(v)], !p.name.isEmpty {
+ out[n] = p.name
} else if let g = s.voiceGuesses?[String(v)] {
out[n] = g.name
}
@@ -240,10 +299,11 @@ enum SpeakerLabels {
return out
}
+
/// Speaker number → Ling's guess, for the voices whose shown name is that guess.
static func guessed(_ s: Session) -> [Int: VoiceGuess] {
var out: [Int: VoiceGuess] = [:]
- for (v, n) in voiceNumbers(s.lines) where s.voiceNames?[String(v)] == nil {
+ for (v, n) in voiceNumbers(s.lines, known: knownVoices(s)) where s.voiceNames?[String(v)] == nil {
if let g = s.voiceGuesses?[String(v)] { out[n] = g }
}
return out
@@ -287,6 +347,12 @@ enum SpeakerLabels {
static func shownCount(_ lines: [TranscriptLine]) -> Int { Set(numbers(lines).values).count }
}
+/// A voice for one line, plus the profile it matched (if any).
+struct SpeakerAssignment: Equatable {
+ var voice: Int?
+ var match: SpeakerProfileMatch?
+}
+
/// Runs voiceprints off the main thread and hands back a voice per line, in arrival order.
@MainActor
final class SpeakerTagger {
@@ -294,24 +360,61 @@ final class SpeakerTagger {
private nonisolated(unsafe) var model: Voiceprints?
private nonisolated(unsafe) var loadFailed = false
private nonisolated(unsafe) var clusterer = VoiceClusterer()
+ /// Local voice id -> profile id. Cleared with the clusterer at the start of a meeting.
+ private nonisolated(unsafe) var voiceProfiles: [Int: UUID] = [:]
+ /// A suggestion is sent once per local voice, not on every line.
+ private nonisolated(unsafe) var suggestedVoices: Set<Int> = []
+ var profiles: SpeakerProfileStore?
+ var policy = SpeakerMatchPolicy()
var onVoice: ((_ lineID: String, _ voice: Int) -> Void)?
+ var onProfile: ((_ lineID: String, _ voice: Int, _ match: SpeakerProfileMatch) -> Void)?
+ var onSuggestion: ((_ lineID: String, _ voice: Int, _ match: SpeakerProfileMatch) -> Void)?
- /// A new meeting: forget the voices of the last one.
- func reset() { queue.async { [self] in clusterer = VoiceClusterer() } }
+ /// A new meeting: forget the voices of the last one. Global profiles stay in the store.
+ func reset() {
+ queue.async { [self] in
+ clusterer = VoiceClusterer()
+ voiceProfiles = [:]
+ suggestedVoices = []
+ }
+ }
func merge(_ from: Int, into: Int) { queue.async { [self] in clusterer.merge(from, into: into) } }
+ /// Start using a profile for an existing local voice after the user accepted a suggestion.
+ func bind(voice: Int, profile: SpeakerProfile) {
+ queue.async { [self] in
+ voiceProfiles[voice] = profile.id
+ suggestedVoices.insert(voice)
+ clusterer.adopt(profile.embedding, into: voice)
+ }
+ }
+
+ /// The unit centroid of a voice, for enrolling it in the profile library.
+ func centroid(voice: Int, _ done: @escaping @MainActor ([Float]?) -> Void) {
+ queue.async { [self] in
+ let v = clusterer.centroid(voice)
+ DispatchQueue.main.async { MainActor.assumeIsolated { done(v) } }
+ }
+ }
+
/// `done` once the line has its voice, or is known to have none.
func tag(lineID: String, samples: [Float], done: @escaping @MainActor () -> Void = {}) {
- voice(of: samples) { [weak self] voice in
- if let voice { self?.onVoice?(lineID, voice) }
+ voice(of: samples) { [weak self] assignment in
+ if let voice = assignment.voice { self?.onVoice?(lineID, voice) }
+ if let voice = assignment.voice, let match = assignment.match {
+ if match.kind == .auto { self?.onProfile?(lineID, voice, match) }
+ else { self?.onSuggestion?(lineID, voice, match) }
+ }
done()
}
}
/// The voice of a line not recorded yet; nil when unsure. Like `tag`, it counts towards that voice.
- func voice(of samples: [Float], _ done: @escaping @MainActor (Int?) -> Void) {
+ func voice(of samples: [Float], _ done: @escaping @MainActor (SpeakerAssignment) -> Void) {
let seconds = Double(samples.count) / 16000
+ let profiles = profiles
+ let policy = policy
queue.async { [self] in
if model == nil, !loadFailed {
do { model = try Voiceprints.load() } catch {
@@ -319,8 +422,38 @@ final class SpeakerTagger {
debugLog("voiceprint model failed to load: \(error)")
}
}
- let voice = model.flatMap { $0.embed(samples) }.flatMap { clusterer.label($0, seconds: seconds) }
- DispatchQueue.main.async { MainActor.assumeIsolated { done(voice) } }
+ guard let embedding = model.flatMap({ $0.embed(samples) }) else {
+ DispatchQueue.main.async { MainActor.assumeIsolated { done(SpeakerAssignment()) } }
+ return
+ }
+ var voice: Int?
+ var matched = profiles?.match(embedding, policy: policy)
+ if let match = matched, match.kind == .auto {
+ if let existing = voiceProfiles.first(where: { $0.value == match.profile.id })?.key {
+ voice = existing
+ matched = nil // already named in this meeting
+ } else if let nearby = clusterer.closest(to: match.profile.embedding, minimum: VoiceClusterer.join),
+ let bound = voiceProfiles[nearby] {
+ // The matching cluster already belongs to someone else: never silently move it.
+ voice = clusterer.label(embedding, seconds: seconds)
+ matched = bound == match.profile.id ? nil : matched.flatMap {
+ SpeakerProfileMatch(profile: $0.profile, similarity: $0.similarity, kind: .suggested)
+ }
+ } else {
+ let nearby = clusterer.closest(to: match.profile.embedding, minimum: VoiceClusterer.join)
+ voice = nearby ?? clusterer.seed(match.profile.embedding)
+ if let voice { voiceProfiles[voice] = match.profile.id }
+ }
+ } else {
+ voice = clusterer.label(embedding, seconds: seconds)
+ if let v = voice, matched != nil, voiceProfiles[v] != nil { matched = nil }
+ }
+ if let match = matched, let v = voice, match.kind == .suggested, suggestedVoices.contains(v) {
+ matched = nil // already offered for this voice
+ }
+ if let match = matched, match.kind == .suggested, let v = voice { suggestedVoices.insert(v) }
+ let assignment = SpeakerAssignment(voice: voice, match: matched)
+ DispatchQueue.main.async { MainActor.assumeIsolated { done(assignment) } }
}
}
}
@@ -332,7 +465,7 @@ final class SpeakerTagger {
enum SpeakerNameGuess {
/// The transcript as Ling sees it, newest 400 lines, with speaker labels; nil when no voices are shown.
static func content(_ s: Session) -> String? {
- let numbers = SpeakerLabels.numbers(s.lines)
+ let numbers = SpeakerLabels.numbers(s)
guard !numbers.isEmpty else { return nil }
let lines = s.lines.suffix(400)
var out = "Meeting transcript. Speakers: 你 = the user; 说话人N = one person on the other side, told apart by voice; 对方 = someone on the other side, not identified.\n"
@@ -373,7 +506,7 @@ enum SpeakerNameGuess {
guard let data = text.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let list = obj["speakers"] as? [[String: Any]] else { return ([:], [:]) }
- let voiceOf = Dictionary(uniqueKeysWithValues: SpeakerLabels.voiceNumbers(s.lines).map { ($1, $0) })
+ let voiceOf = Dictionary(uniqueKeysWithValues: SpeakerLabels.voiceNumbers(s).map { ($1, $0) })
let lines = Array(s.lines.suffix(400))
func count(_ v: Int) -> Int { s.lines.filter { $0.voice == v }.count }
var out: [Int: VoiceGuess] = [:], refuted: [Int: String] = [:]
@@ -442,7 +575,7 @@ final class SpeakerNamer: ObservableObject {
guard ling.hasKey, !busy.contains(id), let s = store.session(id) else { return }
guard force || s.lines.count >= (askedAt[id] ?? -1000) + 20, let content = SpeakerNameGuess.content(s) else { return }
// Everyone already has a name the user gave: nothing to ask.
- let numbers = SpeakerLabels.voiceNumbers(s.lines)
+ let numbers = SpeakerLabels.voiceNumbers(s)
if numbers.keys.allSatisfy({ s.voiceNames?[String($0)] != nil }) { return }
busy.insert(id)
askedAt[id] = s.lines.count
diff --git a/Sources/Cicada/SpeakerLibraryView.swift b/Sources/Cicada/SpeakerLibraryView.swift
new file mode 100644
index 0000000..942d0d6
--- /dev/null
+++ b/Sources/Cicada/SpeakerLibraryView.swift
@@ -0,0 +1,117 @@
+import AppKit
+import SwiftUI
+
+/// The local voiceprint library. Voiceprints are biometric data: every row can be removed here,
+/// and nothing is uploaded.
+struct SpeakerLibraryView: View {
+ @ObservedObject var model: AppModel
+ @State private var editing: UUID?
+ @State private var draft = ""
+ @Environment(\.dismiss) private var dismiss
+
+ private var profiles: [SpeakerProfile] { model.speakerProfiles }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(L("声纹库")).font(.system(size: 20, weight: .bold)).foregroundStyle(Palette.ink)
+ Text(L("只保存在这台 Mac;删除后,以前的会议记录不会受影响。"))
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer()
+ Button(L("完成")) { dismiss() }.buttonStyle(.plain)
+ .font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.accentInk)
+ }
+
+ if profiles.isEmpty {
+ VStack(spacing: 8) {
+ Image(systemName: "person.2.badge.key").font(.system(size: 26)).foregroundStyle(Palette.tertiary)
+ Text(L("还没有记住的人")).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text(L("在会议里点一个说话人,选“记住这个声音”,下次就会自动认出。"))
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ }
+ .frame(maxWidth: .infinity, minHeight: 180)
+ } else {
+ ScrollView {
+ VStack(spacing: 0) {
+ ForEach(profiles) { p in
+ HStack(spacing: 12) {
+ Circle().fill(Palette.accentPale).frame(width: 28, height: 28)
+ .overlay(Text(String(p.name.prefix(1))).font(.system(size: 12, weight: .bold))
+ .foregroundStyle(Palette.accentInk))
+ VStack(alignment: .leading, spacing: 2) {
+ if editing == p.id {
+ TextField(L("名字"), text: $draft)
+ .textFieldStyle(.roundedBorder)
+ .onSubmit { save(p) }
+ } else {
+ Text(p.name).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ }
+ Text(L("\(p.sampleCount) 段样本 · 最近 \(seen(p.lastSeenAt))"))
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer()
+ if editing == p.id {
+ SoftButton(L("保存"), dark: true) { save(p) }
+ Button(L("取消")) { editing = nil }.buttonStyle(.plain)
+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ } else {
+ Button(L("改名")) { editing = p.id; draft = p.name }.buttonStyle(.plain)
+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ Button(L("删除")) { delete(p) }.buttonStyle(.plain)
+ .font(.system(size: 12)).foregroundStyle(Palette.accentInk)
+ }
+ }
+ .padding(.horizontal, 12).frame(minHeight: 54)
+ Divider().padding(.leading, 52)
+ }
+ }
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+ HStack {
+ Text(L("共 \(profiles.count) 个人")).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ Spacer()
+ Button(L("全部删除")) { deleteAll() }.buttonStyle(.plain)
+ .font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.accentInk)
+ }
+ }
+ }
+ .padding(24)
+ .frame(width: 520, height: 440)
+ .background(Color(red: 0.965, green: 0.969, blue: 0.976))
+ }
+
+ private func save(_ p: SpeakerProfile) {
+ model.renameSpeakerProfile(id: p.id, to: draft)
+ editing = nil
+ }
+
+ private func delete(_ p: SpeakerProfile) {
+ let a = NSAlert()
+ a.messageText = L("删除“\(p.name)”的声纹?")
+ a.informativeText = L("之后的会议不会再自动认出这个人;已经生成的记录保持原样。")
+ a.addButton(withTitle: L("删除"))
+ a.addButton(withTitle: L("取消"))
+ if a.runModal() == .alertFirstButtonReturn { model.deleteSpeakerProfile(id: p.id) }
+ }
+
+ private func deleteAll() {
+ let a = NSAlert()
+ a.messageText = L("删除全部声纹?")
+ a.informativeText = L("之后所有会议都不会再自动认出人;已有记录保持原样。")
+ a.addButton(withTitle: L("全部删除"))
+ a.addButton(withTitle: L("取消"))
+ if a.runModal() == .alertFirstButtonReturn { model.deleteAllSpeakerProfiles() }
+ }
+
+ private func seen(_ date: Date?) -> String {
+ guard let date else { return L("还没在新会议里出现") }
+ let f = RelativeDateTimeFormatter()
+ f.locale = uiLocale
+ f.unitsStyle = .short
+ return f.localizedString(for: date, relativeTo: Date())
+ }
+}
diff --git a/Sources/Cicada/SpeakerProfiles.swift b/Sources/Cicada/SpeakerProfiles.swift
new file mode 100644
index 0000000..1475a7e
--- /dev/null
+++ b/Sources/Cicada/SpeakerProfiles.swift
@@ -0,0 +1,273 @@
+import Foundation
+
+/// A known voice: the name the user gave it and the voiceprint it is recognised by.
+/// Kept only on this Mac, in Application Support (never in a meeting record).
+struct SpeakerProfile: Codable, Identifiable, Equatable {
+ let id: UUID
+ var name: String
+ /// 256-d, L2-normalised WeSpeaker embedding (`Voiceprints.embed`).
+ var embedding: [Float]
+ var sampleCount: Int
+ var createdAt: Date
+ var updatedAt: Date
+ var lastSeenAt: Date?
+ /// When the user agreed to keep this voice. Absent for a profile made before this field existed.
+ var consentAt: Date?
+}
+
+/// What a meeting remembers about a local voice id: enough to show the name even if the global
+/// profile is later renamed or deleted.
+struct VoiceProfileRef: Codable, Equatable {
+ var id: UUID
+ var name: String
+ /// The similarity that first matched it (0…1).
+ var similarity: Float
+}
+
+enum SpeakerMatchKind: Equatable {
+ /// Similar enough to name without asking.
+ case auto
+ /// Shown as a suggestion; the user decides.
+ case suggested
+}
+
+struct SpeakerProfileMatch: Equatable {
+ let profile: SpeakerProfile
+ let similarity: Float
+ let kind: SpeakerMatchKind
+
+ var ref: VoiceProfileRef {
+ VoiceProfileRef(id: profile.id, name: profile.name, similarity: similarity)
+ }
+}
+
+/// Starting thresholds for the 256-d WeSpeaker model. `VoiceClusterer`'s 0.5 is a within-meeting
+/// threshold and must not be reused for identity: a wrong name in a customer's minutes is worse
+/// than "未识别". These are deliberately conservative and are covered by tests with the bundled
+/// sample; tune on real meetings before lowering them.
+struct SpeakerMatchPolicy: Equatable {
+ var auto: Float = 0.70
+ var suggested: Float = 0.55
+ /// The best profile must be this much ahead of the second one before it may be named silently.
+ var margin: Float = 0.08
+}
+
+/// Vector helpers shared by the clusterer, the profile store and tests.
+enum SpeakerEmbedding {
+ static let dimensions = 256
+
+ static func normalized(_ v: [Float]) -> [Float]? {
+ guard v.count == dimensions else { return nil }
+ var sum: Float = 0
+ for x in v { sum += x * x }
+ guard sum.isFinite, sum > 0 else { return nil }
+ let scale = sum.squareRoot()
+ let out = v.map { $0 / scale }
+ return out.allSatisfy(\.isFinite) ? out : nil
+ }
+
+ /// Dot product; both vectors are unit length, so this is their cosine similarity.
+ static func cosine(_ a: [Float], _ b: [Float]) -> Float? {
+ guard a.count == dimensions, b.count == dimensions else { return nil }
+ var dot: Float = 0
+ for i in 0..<dimensions { dot += a[i] * b[i] }
+ return dot.isFinite ? dot : nil
+ }
+
+ /// Unit-length mean of unit vectors, without letting a short noisy clip dominate.
+ static func mean(_ vectors: [[Float]]) -> [Float]? {
+ guard !vectors.isEmpty else { return nil }
+ var sum = [Float](repeating: 0, count: dimensions)
+ for v in vectors {
+ guard v.count == dimensions else { continue }
+ for i in 0..<dimensions { sum[i] += v[i] }
+ }
+ return normalized(sum)
+ }
+
+ /// A new sample joins an existing profile gradually: `normalize(old * weight + fresh)`.
+ /// The weight is capped so a profile cannot become impossible to correct after years of use.
+ static func blended(old: [Float], fresh: [Float], sampleCount: Int) -> [Float]? {
+ guard old.count == dimensions, fresh.count == dimensions else { return nil }
+ let weight = Float(min(max(1, sampleCount), 20))
+ var sum = [Float](repeating: 0, count: dimensions)
+ for i in 0..<dimensions { sum[i] = old[i] * weight + fresh[i] }
+ return normalized(sum)
+ }
+}
+
+/// The persistent voiceprint library. Reads may happen on the voiceprint queue; changes happen on
+/// the main actor. A lock keeps a snapshot safe while a profile is being written.
+final class SpeakerProfileStore: @unchecked Sendable {
+ let url: URL
+ private let lock = NSLock()
+ private var cached: [SpeakerProfile] = []
+
+ /// Called after a change, with a snapshot; AppModel refreshes its `@Published` copy here.
+ var onChange: (([SpeakerProfile]) -> Void)?
+
+ static var defaultURL: URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent(DevBuild.supportFolder)
+ .appendingPathComponent("VoiceProfiles", isDirectory: true)
+ .appendingPathComponent("profiles.json")
+ }
+
+ init(url: URL = SpeakerProfileStore.defaultURL) {
+ self.url = url
+ cached = Self.load(from: url)
+ try? Self.protectDirectory(url.deletingLastPathComponent())
+ try? Self.protectFile(url)
+ for p in cached where p.consentAt == nil { try? markConsent(p.id, at: p.createdAt) }
+ }
+
+ func all() -> [SpeakerProfile] {
+ lock.lock()
+ defer { lock.unlock() }
+ return cached.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ }
+
+ /// A sorted snapshot for matching; does not expose the live array.
+ func snapshot() -> [SpeakerProfile] {
+ lock.lock()
+ defer { lock.unlock() }
+ return cached
+ }
+
+ /// Best profile above `suggested`, with high-confidence hits distinguished from suggestions.
+ func match(_ embedding: [Float], policy: SpeakerMatchPolicy = SpeakerMatchPolicy()) -> SpeakerProfileMatch? {
+ guard let probe = SpeakerEmbedding.normalized(embedding) else { return nil }
+ let profiles = snapshot()
+ .filter { $0.embedding.count == SpeakerEmbedding.dimensions && !$0.name.isEmpty }
+ .compactMap { p -> (SpeakerProfile, Float)? in
+ guard let v = SpeakerEmbedding.normalized(p.embedding),
+ let score = SpeakerEmbedding.cosine(probe, v) else { return nil }
+ return (p, score)
+ }
+ .sorted { $0.1 > $1.1 }
+ guard let best = profiles.first, best.1 >= policy.suggested else { return nil }
+ let second = profiles.dropFirst().first?.1
+ let clear = second == nil || (best.1 - second!) >= policy.margin
+ return SpeakerProfileMatch(profile: best.0, similarity: best.1,
+ kind: best.1 >= policy.auto && clear ? .auto : .suggested)
+ }
+
+ /// Add a profile from an explicit user action. Returns nil when the embedding is unusable or
+ /// the name is empty; the caller must not silently fall back to a profile with no name.
+ @discardableResult
+ func remember(name: String, embedding: [Float], at date: Date = Date()) -> SpeakerProfile? {
+ let clean = Self.cleanName(name)
+ guard !clean.isEmpty, let v = SpeakerEmbedding.normalized(embedding) else { return nil }
+ let p = SpeakerProfile(id: UUID(), name: clean, embedding: v, sampleCount: 1,
+ createdAt: date, updatedAt: date, lastSeenAt: nil, consentAt: date)
+ mutate { $0.append(p) }
+ return p
+ }
+
+ @discardableResult
+ func updateEmbedding(id: UUID, embedding: [Float], at date: Date = Date()) -> Bool {
+ guard let v = SpeakerEmbedding.normalized(embedding) else { return false }
+ var updated = false
+ mutate { profiles in
+ guard let i = profiles.firstIndex(where: { $0.id == id }),
+ let blended = SpeakerEmbedding.blended(old: profiles[i].embedding, fresh: v,
+ sampleCount: profiles[i].sampleCount) else { return }
+ profiles[i].embedding = blended
+ profiles[i].sampleCount += 1
+ profiles[i].updatedAt = date
+ updated = true
+ }
+ return updated
+ }
+
+ @discardableResult
+ func rename(id: UUID, to name: String, at date: Date = Date()) -> Bool {
+ let clean = Self.cleanName(name)
+ guard !clean.isEmpty else { return false }
+ var updated = false
+ mutate { profiles in
+ guard let i = profiles.firstIndex(where: { $0.id == id }) else { return }
+ profiles[i].name = clean
+ profiles[i].updatedAt = date
+ updated = true
+ }
+ return updated
+ }
+
+ func delete(id: UUID) {
+ mutate { $0.removeAll { $0.id == id } }
+ }
+
+ func deleteAll() {
+ mutate { $0.removeAll() }
+ }
+
+ /// Make a matched profile's last-seen time current. Writes at most once a minute per profile,
+ /// so matching a line every few seconds does not hammer the disk.
+ func markSeen(id: UUID, at date: Date = Date()) {
+ let old = snapshot().first { $0.id == id }?.lastSeenAt
+ guard old == nil || date.timeIntervalSince(old!) > 60 else { return }
+ mutate { profiles in
+ guard let i = profiles.firstIndex(where: { $0.id == id }) else { return }
+ profiles[i].lastSeenAt = date
+ }
+ }
+
+ private func markConsent(_ id: UUID, at date: Date) throws {
+ mutate { profiles in
+ guard let i = profiles.firstIndex(where: { $0.id == id }), profiles[i].consentAt == nil else { return }
+ profiles[i].consentAt = date
+ }
+ }
+
+ private func mutate(_ change: (inout [SpeakerProfile]) -> Void) {
+ lock.lock()
+ change(&cached)
+ let snapshot = cached
+ lock.unlock()
+ save(snapshot)
+ onChange?(snapshot)
+ }
+
+ private func save(_ profiles: [SpeakerProfile]) {
+ do {
+ let dir = url.deletingLastPathComponent()
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try Self.protectDirectory(dir)
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(profiles)
+ try data.write(to: url, options: .atomic)
+ try Self.protectFile(url)
+ } catch {
+ debugLog("voice profiles: save failed \(error)")
+ }
+ }
+
+ private static func load(from url: URL) -> [SpeakerProfile] {
+ guard let data = try? Data(contentsOf: url) else { return [] }
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ guard let decoded = try? decoder.decode([SpeakerProfile].self, from: data) else { return [] }
+ // A damaged entry must not take the whole library, or the app, down with it.
+ return decoded.filter {
+ !$0.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ && $0.embedding.count == SpeakerEmbedding.dimensions
+ }
+ }
+
+ private static func cleanName(_ name: String) -> String {
+ let clean = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ return String(clean.prefix(40))
+ }
+
+ private static func protectDirectory(_ url: URL) throws {
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)
+ }
+
+ private static func protectFile(_ url: URL) throws {
+ guard FileManager.default.fileExists(atPath: url.path) else { return }
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
+ }
+}
diff --git a/Sources/Cicada/SpeakerViews.swift b/Sources/Cicada/SpeakerViews.swift
index 804558a..625e455 100644
--- a/Sources/Cicada/SpeakerViews.swift
+++ b/Sources/Cicada/SpeakerViews.swift
@@ -79,7 +79,7 @@ struct SpeakerStrip: View {
@State private var popover: Int?
var body: some View {
- let numbers = SpeakerLabels.voiceNumbers(session.lines)
+ let numbers = SpeakerLabels.voiceNumbers(session)
let names = SpeakerLabels.names(session)
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 8) {
@@ -143,10 +143,11 @@ struct SpeakerEditor: View {
var body: some View {
// Gone once merged into someone else: the editor closes on the next turn.
- if let s = session, let n = SpeakerLabels.voiceNumbers(s.lines)[voice] {
- let numbers = SpeakerLabels.voiceNumbers(s.lines)
+ if let s = session, let n = SpeakerLabels.voiceNumbers(s)[voice] {
+ let numbers = SpeakerLabels.voiceNumbers(s)
let names = SpeakerLabels.names(s)
let guess = SpeakerLabels.guessed(s)[n]
+ let suggestion = model.speakerSuggestion(session: s.id, voice: voice)
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 6) {
Circle().fill(SpeakerColor.ink(n)).frame(width: 8, height: 8)
@@ -202,6 +203,68 @@ struct SpeakerEditor: View {
Text("Ling 正在从对话里找名字…").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
}
}
+ if let suggestion {
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: "person.crop.circle.badge.checkmark")
+ .font(.system(size: 13)).foregroundStyle(Palette.accentInk)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(L("声纹库:可能是 \(suggestion.name)(\(Int((suggestion.similarity * 100).rounded()))%)"))
+ .font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text(L("声音像,但还不够确定。确认后,下次会议会直接认出。"))
+ .font(.system(size: 10)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer(minLength: 6)
+ Button(L("是 TA")) {
+ model.acceptSpeakerSuggestion(session: s.id, voice: voice)
+ close()
+ }
+ .buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk)
+ Button(L("不是")) {
+ model.dismissSpeakerSuggestion(session: s.id, voice: voice)
+ }
+ .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.secondary)
+ }
+ .padding(8)
+ .background(RoundedRectangle(cornerRadius: 8).fill(Palette.accentPale.opacity(0.55)))
+ } else if let known = s.voiceProfiles?[String(voice)] {
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: "person.crop.circle.badge.checkmark")
+ .font(.system(size: 13)).foregroundStyle(Palette.accentInk)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(L("声纹库:\(known.name)"))
+ .font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text(L("这次会议按这个声纹标的。认错了可以只断开本次,不会删掉声纹。"))
+ .font(.system(size: 10)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer(minLength: 6)
+ Button(L("更新声纹")) {
+ model.rememberSpeaker(session: s.id, voice: voice, name: known.name)
+ }
+ .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.secondary)
+ Button(L("不是 TA")) {
+ model.forgetSpeaker(session: s.id, voice: voice)
+ }
+ .buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk)
+ }
+ } else {
+ HStack(spacing: 8) {
+ Button {
+ model.rememberSpeaker(session: s.id, voice: voice, name: draft.isEmpty ? nil : draft)
+ } label: {
+ HStack(spacing: 5) {
+ Image(systemName: "person.badge.plus").font(.system(size: 10))
+ Text(model.speakerMemoryBusy ? L("正在记住…") : L("记住这个声音"))
+ .font(.system(size: 11, weight: .semibold))
+ }
+ .foregroundStyle(Palette.accentInk).padding(.horizontal, 9).frame(height: 26)
+ .background(RoundedRectangle(cornerRadius: 7).fill(Palette.accentPale))
+ }
+ .buttonStyle(.plain)
+ .disabled(model.speakerMemoryBusy)
+ .help(L("需要 3 句以上发言;声纹只保存在这台 Mac"))
+ Text(L("下次会议自动认出")).font(.system(size: 10)).foregroundStyle(Palette.tertiary)
+ }
+ }
let others = numbers.filter { $0.key != voice }.sorted { $0.value < $1.value }
if !others.isEmpty {
VStack(alignment: .leading, spacing: 6) {
@@ -337,7 +400,7 @@ struct SpeakerPreview: View {
@ObservedObject var model: AppModel
let session: Session
var body: some View {
- let numbers = SpeakerLabels.numbers(session.lines)
+ let numbers = SpeakerLabels.numbers(session)
let starts = SpeakerLabels.runStarts(session.lines, numbers)
VStack(alignment: .leading, spacing: 10) {
if !numbers.isEmpty { SpeakerStrip(model: model, session: session) }
diff --git a/Sources/Cicada/Views.swift b/Sources/Cicada/Views.swift
index 5d1db79..8c03de0 100644
--- a/Sources/Cicada/Views.swift
+++ b/Sources/Cicada/Views.swift
@@ -1319,7 +1319,7 @@ struct MainWindowView: View {
.buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
}
.padding(.bottom, 8)
- let speakers = settings.speakerVoices ? SpeakerLabels.numbers(s.lines) : [:]
+ let speakers = settings.speakerVoices ? SpeakerLabels.numbers(s) : [:]
let starts = SpeakerLabels.runStarts(s.lines, speakers)
ForEach(s.lines) { l in
quoteRow(l, speaker: speakers[l.id], picked: quoteJump.map { t in l.id == pickedLine(s, t)?.id } ?? false,
@@ -1384,12 +1384,12 @@ struct MainWindowView: View {
.id(PinnedHeader.top)
.pinnedHeader($pinned)
LazyVStack(alignment: .leading, spacing: 0) {
- let speakers = settings.speakerVoices ? SpeakerLabels.numbers(s.lines) : [:]
+ let speakers = settings.speakerVoices ? SpeakerLabels.numbers(s) : [:]
if !speakers.isEmpty { SpeakerStrip(model: model, session: s).padding(.bottom, 8) }
let both = RecordList.heardBoth(s.lines)
// In a meeting that heard the room and the Mac, a change of place starts a new run too.
let starts = SpeakerLabels.runStarts(s.lines, speakers).union(both ? RecordList.placeStarts(s.lines) : [])
- let voices = SpeakerLabels.voiceNumbers(s.lines)
+ let voices = SpeakerLabels.voiceNumbers(s)
let playingLine = player.lineID(in: s)
if s.id != store.liveID {
FixReviewBanner(fixes: model.fixes, session: s, onShow: { id in withAnimation { proxy.scrollTo(id, anchor: .center) } },
@@ -1492,7 +1492,7 @@ struct MainWindowView: View {
if !label {
} else if voices, !me, let s = shownSession {
// A click on whose line it is: say it was someone else's.
- Menu { assignMenu(s, l, SpeakerLabels.voiceNumbers(s.lines)) } label: {
+ Menu { assignMenu(s, l, SpeakerLabels.voiceNumbers(s)) } label: {
if let speaker { SpeakerTag(number: speaker) } else { UnknownSpeakerTag() }
}
.menuStyle(.borderlessButton).menuIndicator(.visible).fixedSize()
diff --git a/Tests/CicadaTests/SpeakerProfileTests.swift b/Tests/CicadaTests/SpeakerProfileTests.swift
new file mode 100644
index 0000000..51018a1
--- /dev/null
+++ b/Tests/CicadaTests/SpeakerProfileTests.swift
@@ -0,0 +1,155 @@
+import Foundation
+import Testing
+@testable import Cicada
+
+@Suite struct SpeakerProfileTests {
+ private func unit(_ index: Int, noise: Float = 0) -> [Float] {
+ var v = [Float](repeating: noise, count: SpeakerEmbedding.dimensions)
+ v[index] = 1
+ return v
+ }
+
+ private func store() throws -> (SpeakerProfileStore, URL) {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-profiles-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return (SpeakerProfileStore(url: root.appendingPathComponent("profiles.json")), root)
+ }
+
+ @Test func rememberMatchAndDelete() throws {
+ let (s, root) = try store()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let p = try #require(s.remember(name: "张总", embedding: unit(0)))
+ #expect(s.all().count == 1)
+ #expect(s.match(unit(0, noise: 0.01))?.kind == .auto)
+ #expect(s.match(unit(1)) == nil)
+ let attrs = try FileManager.default.attributesOfItem(atPath: s.url.path)
+ #expect((attrs[.posixPermissions] as? NSNumber)?.intValue == 0o600)
+ // A fresh process reads the profile back, dates included.
+ #expect(SpeakerProfileStore(url: s.url).all().map(\.name) == ["张总"])
+ s.delete(id: p.id)
+ #expect(s.all().isEmpty)
+ }
+
+ @Test func aCloseMatchIsOnlySuggested() throws {
+ let (s, root) = try store()
+ defer { try? FileManager.default.removeItem(at: root) }
+ _ = s.remember(name: "A", embedding: unit(0))
+ _ = s.remember(name: "B", embedding: unit(1))
+ // 0.62 toward A, 0.60 toward B: above suggested, below auto, and not a clear winner.
+ let mixed = (0..<SpeakerEmbedding.dimensions).map { i in
+ i == 0 ? Float(0.62) : (i == 1 ? Float(0.60) : 0)
+ }
+ let m = try #require(s.match(mixed))
+ #expect(m.kind == .suggested)
+ }
+
+ @Test func blendedProfileMovesGradually() throws {
+ let (s, root) = try store()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let p = try #require(s.remember(name: "A", embedding: unit(0)))
+ #expect(s.updateEmbedding(id: p.id, embedding: unit(0, noise: 0.02)))
+ let after = try #require(s.snapshot().first)
+ #expect(after.sampleCount == 2)
+ #expect(after.embedding[0] > 0.9)
+ }
+
+ @Test func corruptLibraryIsEmptyNotFatal() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-profiles-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try Data("not json".utf8).write(to: root.appendingPathComponent("profiles.json"))
+ #expect(SpeakerProfileStore(url: root.appendingPathComponent("profiles.json")).all().isEmpty)
+ }
+
+ @Test func aKnownVoiceShowsBeforeFiveLines() {
+ let line = TranscriptLine(id: "l0", t: 1, speaker: "them", src: "我们周四上线",
+ dst: nil, srcLang: "zh-CN", dstLang: "en", voice: 2)
+ let s = Session(id: "s", title: "t", startedAt: Date(), endedAt: nil, lines: [line], hasAudio: false,
+ notes: nil, voiceProfiles: ["2": VoiceProfileRef(id: UUID(), name: "张总", similarity: 0.8)])
+ #expect(SpeakerLabels.numbers(s) == ["l0": 1])
+ #expect(SpeakerLabels.names(s) == [1: "张总"])
+ }
+
+ @Test func oldSessionJSONStillDecodes() throws {
+ let json = """
+ {"id":"old","title":"会议","startedAt":"2026-01-01T00:00:00Z","lines":[],"hasAudio":false}
+ """
+ let d = JSONDecoder()
+ d.dateDecodingStrategy = .iso8601
+ let s = try d.decode(Session.self, from: Data(json.utf8))
+ #expect(s.id == "old")
+ #expect(s.voiceProfiles == nil)
+ }
+
+ @Test func pooledSampleVoicesMatchThemselvesAndNotEachOther() throws {
+ let repo = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let audio = repo.appendingPathComponent("Resources/sample/sample.m4a")
+ let modelURL = repo.appendingPathComponent("Resources/models/SpeakerEmbedding.mlpackage")
+ let all = try #require(Voiceprints.samples(of: audio))
+ let rate = 16_000.0
+ func clip(_ start: Double, _ end: Double) -> [Float] {
+ Array(all[Int(start * rate)..<min(all.count, Int(end * rate))])
+ }
+ let model = try Voiceprints.load(packageURL: modelURL)
+ let emma1 = try #require(model.embed(clip(0.25, 1.30)))
+ let emma2 = try #require(model.embed(clip(7.17, 8.40)))
+ let george = try #require(model.embed(clip(2.56, 4.70)))
+ let same = try #require(SpeakerEmbedding.cosine(emma1, emma2))
+ let other = try #require(SpeakerEmbedding.cosine(emma1, george))
+ #expect(same > other)
+ }
+
+ /// A real model + real audio path, using two macOS system voices: the same voice should
+ /// enrol and match across two recordings, a different voice should stay anonymous.
+ @Test func enrollmentAndCrossMeetingMatchWithRealAudio() async throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-tts-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ func say(_ file: String, _ voice: String, _ text: String) throws -> URL {
+ let url = dir.appendingPathComponent(file)
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/say")
+ p.arguments = ["-v", voice, "-o", url.path, text]
+ try p.run()
+ p.waitUntilExit()
+ guard p.terminationStatus == 0, FileManager.default.fileExists(atPath: url.path) else {
+ throw CocoaError(.fileReadNoSuchFile)
+ }
+ return url
+ }
+ let long = "Today we are reviewing the project schedule, the budget, and the next steps. "
+ + "Please write down the decisions and the owners, and send the notes to the team tomorrow morning."
+ let first = try say("first.aiff", "Samantha", long)
+ let second = try say("second.aiff", "Samantha", long + " We will meet again on Friday.")
+ let other = try say("other.aiff", "Fred", long)
+ let modelURL = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("Resources/models/SpeakerEmbedding.mlpackage")
+ let started = Date()
+ func session(_ voice: Int) -> Session {
+ let texts = ["We should review the project schedule and the budget today.",
+ "Please write down the decisions and the owners in the notes.",
+ "Send the notes to the team tomorrow morning, before the next meeting."]
+ let times = [0.2, 3.8, 7.4]
+ let lines = zip(times, texts).enumerated().map { i, pair in
+ TranscriptLine(id: "l\(i)", t: pair.0, speaker: "them", src: pair.1, dst: nil,
+ srcLang: "en", dstLang: "zh-CN", voice: voice)
+ }
+ return Session(id: "s\(voice)", title: "t", startedAt: started,
+ endedAt: started.addingTimeInterval(11.5), lines: lines, hasAudio: true)
+ }
+ let a = try await SpeakerEnrollment.build(session: session(0), voice: 0, audioURL: first, packageURL: modelURL)
+ let b = try await SpeakerEnrollment.build(session: session(0), voice: 0, audioURL: second, packageURL: modelURL)
+ let c = try await SpeakerEnrollment.build(session: session(0), voice: 0, audioURL: other, packageURL: modelURL)
+ let same = try #require(SpeakerEmbedding.cosine(a.embedding, b.embedding))
+ let different = try #require(SpeakerEmbedding.cosine(a.embedding, c.embedding))
+ #expect(a.clips >= 3)
+ #expect(same > 0.70)
+ #expect(different < 0.55)
+ let store = SpeakerProfileStore(url: dir.appendingPathComponent("profiles.json"))
+ let profile = try #require(store.remember(name: "Samantha", embedding: a.embedding))
+ #expect(store.match(b.embedding)?.profile.id == profile.id)
+ #expect(store.match(c.embedding) == nil)
+ }
+}