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(windows): label the other side's lines Speaker 1, 2… by voice, on this PC only

wquguru047997737570
diff --git a/windows/README.md b/windows/README.md
index 3b724af..a1493d1 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -1,6 +1,6 @@
# 知了 Windows 版
-Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。
+Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议);说话人识别(按声音标出说话人 1、2…,声纹模型是 WeSpeaker ResNet34-LM,CC BY 4.0,用 `scripts/compress-voiceprint.py` 压成 int8,6.7 MB,由系统自带的 Windows ML 在本机运行)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。
- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。
- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。
diff --git a/windows/scripts/compress-voiceprint.py b/windows/scripts/compress-voiceprint.py
new file mode 100644
index 0000000..cb4d25f
--- /dev/null
+++ b/windows/scripts/compress-voiceprint.py
@@ -0,0 +1,121 @@
+# Shrinks the WeSpeaker ResNet34-LM voiceprint model (VoxCeleb, CC BY 4.0) for the Windows app:
+# every conv and dense weight becomes int8 with one scale per output channel, turned back into float by a
+# Cast and a Mul when the model loads. Only opset-12 ops, so Windows' built-in Windows ML on
+# Windows 10 2004 runs it; inference stays float32. 26.5 MB → 6.7 MB.
+# Developer-only, run once; the app needs no Python. Needs: onnx numpy (onnxruntime to check).
+# The source is the file the Mac's scripts/convert-voiceprint.py starts from
+# (sha256 7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068).
+# usage: python3 scripts/compress-voiceprint.py voxceleb_resnet34_LM.onnx src/Cicada/Assets/voiceprint.onnx
+import sys, hashlib, numpy as np, onnx
+from onnx import helper, numpy_helper as nh, TensorProto
+
+src, out = sys.argv[1], sys.argv[2]
+# --bits 4 packs two weights per byte (unpacked with Floor/Mul/Sub/Concat, still opset 12).
+bits = int(sys.argv[sys.argv.index("--bits") + 1]) if "--bits" in sys.argv else 8
+levels = 127 if bits == 8 else 7
+assert hashlib.sha256(open(src, "rb").read()).hexdigest() == "7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068", "not the pinned WeSpeaker model"
+m = onnx.load(src)
+g = m.graph
+# Conv weights (out, in, kh, kw) and the embedding layer's Gemm weight (out, in; transB=1): both
+# have output channels first, so one scale per row.
+gemm_ok = all(any(a.name == "transB" and a.i == 1 for a in n.attribute) for n in g.node if n.op_type == "Gemm")
+assert gemm_ok, "expected Gemm with transB=1"
+conv_weights = {n.input[1] for n in g.node if n.op_type in ("Conv", "Gemm")}
+inits = {i.name: i for i in g.initializer}
+new_inits, new_nodes = [], []
+for name in conv_weights:
+ w = nh.to_array(inits[name]).astype(np.float32)
+ flat = np.abs(w.reshape(w.shape[0], -1)).max(axis=1)
+ scale = np.where(flat > 0, flat / levels, 1.0).astype(np.float32)
+ shaped = scale.reshape(-1, *([1] * (w.ndim - 1)))
+ q = np.clip(np.round(w / shaped), -levels, levels).astype(np.int8)
+ g.initializer.remove(inits[name])
+ row = int(np.prod(w.shape[1:]))
+ group = 32
+ if bits == 4 and row % group == 0:
+ # 4-bit, one scale per 32 weights of a row (fp16 scales): fine enough to keep the voice.
+ G = w.reshape(w.shape[0], row // group, group)
+ gs = np.abs(G).max(axis=2, keepdims=True); gs = np.where(gs > 0, gs / 7, 1).astype(np.float16)
+ q4 = np.clip(np.round(G / gs.astype(np.float32)), -7, 7).astype(np.int16) + 8
+ u = q4.reshape(-1).astype(np.uint8)
+ packed = (u[0::2] << 4 | u[1::2]).astype(np.uint8)
+ n = name
+ new_inits += [nh.from_array(packed, n + "_p"), nh.from_array(gs, n + "_s16"),
+ nh.from_array(np.array([16.0], np.float32), n + "_16"), nh.from_array(np.array([8.0], np.float32), n + "_8"),
+ nh.from_array(np.array([w.shape[0], row // group, group], np.int64), n + "_g"), nh.from_array(np.array(w.shape, np.int64), n + "_shape")]
+ new_nodes += [
+ helper.make_node("Cast", [n + "_p"], [n + "_pf"], to=TensorProto.FLOAT),
+ helper.make_node("Div", [n + "_pf", n + "_16"], [n + "_d"]),
+ helper.make_node("Floor", [n + "_d"], [n + "_hi"]),
+ helper.make_node("Mul", [n + "_hi", n + "_16"], [n + "_hi16"]),
+ helper.make_node("Sub", [n + "_pf", n + "_hi16"], [n + "_lo"]),
+ helper.make_node("Unsqueeze", [n + "_hi"], [n + "_hiu"], axes=[1]),
+ helper.make_node("Unsqueeze", [n + "_lo"], [n + "_lou"], axes=[1]),
+ helper.make_node("Concat", [n + "_hiu", n + "_lou"], [n + "_pair"], axis=1),
+ helper.make_node("Reshape", [n + "_pair", n + "_g"], [n + "_grp"]),
+ helper.make_node("Sub", [n + "_grp", n + "_8"], [n + "_c"]),
+ helper.make_node("Cast", [n + "_s16"], [n + "_sf"], to=TensorProto.FLOAT),
+ helper.make_node("Mul", [n + "_c", n + "_sf"], [n + "_w"]),
+ helper.make_node("Reshape", [n + "_w", n + "_shape"], [n]),
+ ]
+ continue
+ if bits == 8 or row % group != 0:
+ if bits == 4: # rows that don't split into groups (the first conv): 8-bit
+ scale = np.where(flat > 0, flat / 127, 1.0).astype(np.float32); shaped = scale.reshape(-1, *([1] * (w.ndim - 1)))
+ q = np.clip(np.round(w / shaped), -127, 127).astype(np.int8)
+ new_inits += [nh.from_array(q, name + "_q"), nh.from_array(shaped, name + "_s")]
+ new_nodes += [helper.make_node("Cast", [name + "_q"], [name + "_f"], to=TensorProto.FLOAT),
+ helper.make_node("Mul", [name + "_f", name + "_s"], [name])]
+ else:
+ u = (q.reshape(-1).astype(np.int16) + 8).astype(np.uint8) # 1…15
+ if u.size % 2: u = np.append(u, np.uint8(8))
+ packed = (u[0::2] << 4 | u[1::2]).astype(np.uint8)
+ n = name
+ new_inits += [nh.from_array(packed, n + "_p"), nh.from_array(shaped, n + "_s"),
+ nh.from_array(np.array([16.0], np.float32), n + "_16"), nh.from_array(np.array([8.0], np.float32), n + "_8"),
+ nh.from_array(np.array([-1], np.int64), n + "_flat"), nh.from_array(np.array(w.shape, np.int64), n + "_shape"),
+ nh.from_array(np.array([0], np.int64), n + "_0"), nh.from_array(np.array([q.size], np.int64), n + "_len")]
+ new_nodes += [
+ helper.make_node("Cast", [n + "_p"], [n + "_pf"], to=TensorProto.FLOAT),
+ helper.make_node("Div", [n + "_pf", n + "_16"], [n + "_d"]),
+ helper.make_node("Floor", [n + "_d"], [n + "_hi"]),
+ helper.make_node("Mul", [n + "_hi", n + "_16"], [n + "_hi16"]),
+ helper.make_node("Sub", [n + "_pf", n + "_hi16"], [n + "_lo"]),
+ helper.make_node("Unsqueeze", [n + "_hi"], [n + "_hiu"], axes=[1]),
+ helper.make_node("Unsqueeze", [n + "_lo"], [n + "_lou"], axes=[1]),
+ helper.make_node("Concat", [n + "_hiu", n + "_lou"], [n + "_pair"], axis=1),
+ helper.make_node("Reshape", [n + "_pair", n + "_flat"], [n + "_all"]),
+ helper.make_node("Slice", [n + "_all", n + "_0", n + "_len"], [n + "_cut"]),
+ helper.make_node("Sub", [n + "_cut", n + "_8"], [n + "_c"]),
+ helper.make_node("Reshape", [n + "_c", n + "_shape"], [n + "_w"]),
+ helper.make_node("Mul", [n + "_w", n + "_s"], [n]),
+ ]
+g.initializer.extend(new_inits)
+nodes = list(g.node)
+del g.node[:]
+g.node.extend(new_nodes + nodes)
+# Unsqueeze took its axes as an attribute before opset 13: move them back from the input.
+consts = {n.output[0]: nh.to_array(n.attribute[0].t) for n in g.node if n.op_type == "Constant"}
+consts.update({i.name: nh.to_array(i) for i in g.initializer})
+for n in g.node:
+ if n.op_type == "Unsqueeze" and len(n.input) == 2:
+ axes = [int(x) for x in np.atleast_1d(consts[n.input[1]])]
+ del n.input[1]
+ n.attribute.append(helper.make_attribute("axes", axes))
+# Every other op here is unchanged since opset 12 (ReduceMean keeps its axes attribute until 18).
+del m.opset_import[:]
+m.opset_import.extend([helper.make_opsetid("", 12)])
+m.ir_version = 7
+onnx.checker.check_model(m)
+onnx.save(m, out)
+print(f"{src}: {sum(nh.to_array(i).nbytes for i in onnx.load(src).graph.initializer) / 1e6:.1f} MB of weights → {out}")
+
+try:
+ import onnxruntime as ort
+ rng = np.random.default_rng(0)
+ feats = rng.standard_normal((1, 300, 80)).astype(np.float32)
+ a = ort.InferenceSession(src).run(None, {"feats": feats})[0][0]
+ b = ort.InferenceSession(out).run(None, {"feats": feats})[0][0]
+ print(f"cosine to the original on noise: {np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b):.5f}")
+except ImportError:
+ pass
diff --git a/windows/scripts/test.sh b/windows/scripts/test.sh
index 4d3724a..dc27646 100755
--- a/windows/scripts/test.sh
+++ b/windows/scripts/test.sh
@@ -2,5 +2,10 @@
# Unit tests for the Windows engines; runs on the Mac and in CI (no network, no Windows needed).
set -euo pipefail
cd "$(dirname "$0")/.."
-scripts/dotnet.sh build tests/Cicada.Tests -o build/tests -v quiet -nologo 2>&1 | grep -E ' error |warning CS' | sort -u || true
+# A failed build must fail here, or the last good binary's results would be reported.
+if ! out=$(scripts/dotnet.sh build tests/Cicada.Tests -o build/tests -v quiet -nologo 2>&1); then
+ echo "$out" | grep -E ' error ' | sort -u >&2
+ exit 1
+fi
+echo "$out" | grep -E 'warning CS' | sort -u || true
DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" build/tests/Cicada.Tests
diff --git a/windows/spike/WinMLProbe/Program.cs b/windows/spike/WinMLProbe/Program.cs
new file mode 100644
index 0000000..956b10a
--- /dev/null
+++ b/windows/spike/WinMLProbe/Program.cs
@@ -0,0 +1,34 @@
+// usage: WinMLProbe <model.onnx> <ref.json> <feats dir>
+// Loads the model with Windows.AI.MachineLearning, embeds each fixture's features, and prints the
+// cosine to the Mac's onnxruntime embedding and the time per clip.
+using System.Diagnostics;
+using System.Text.Json;
+using Windows.AI.MachineLearning;
+
+var model = LearningModel.LoadFromFilePath(Path.GetFullPath(args[0]));
+Console.WriteLine($"loaded: inputs {string.Join(",", model.InputFeatures.Select(f => f.Name))}, outputs {string.Join(",", model.OutputFeatures.Select(f => f.Name))}");
+foreach (var f in model.InputFeatures.OfType<TensorFeatureDescriptor>()) Console.WriteLine($" {f.Name} shape [{string.Join(",", f.Shape)}]");
+var session = new LearningModelSession(model, new LearningModelDevice(LearningModelDeviceKind.Cpu));
+var refs = JsonDocument.Parse(File.ReadAllText(args[1])).RootElement;
+foreach (var clip in refs.EnumerateObject())
+{
+ int frames = clip.Value.GetProperty("frames").GetInt32();
+ var raw = File.ReadAllBytes(Path.Combine(args[2], clip.Name + ".feats.bin"));
+ var feats = new float[raw.Length / 4];
+ Buffer.BlockCopy(raw, 0, feats, 0, raw.Length);
+ float[] emb = [];
+ var times = new List<double>();
+ for (int run = 0; run < 4; run++)
+ {
+ var sw = Stopwatch.StartNew();
+ var binding = new LearningModelBinding(session);
+ binding.Bind("feats", TensorFloat.CreateFromArray([1, frames, 80], feats));
+ var result = await session.EvaluateAsync(binding, "");
+ emb = ((TensorFloat)result.Outputs["embs"]).GetAsVectorView().ToArray();
+ times.Add(sw.Elapsed.TotalMilliseconds);
+ }
+ var norm = MathF.Sqrt(emb.Sum(x => x * x));
+ var reference = clip.Value.GetProperty("emb").EnumerateArray().Select(x => x.GetSingle()).ToArray();
+ var cos = emb.Zip(reference, (a, b) => a / norm * b).Sum();
+ Console.WriteLine($"{clip.Name}: {frames / 100.0:F1} s of speech, cosine to Mac {cos:F5}, first {times[0]:F0} ms, then {times.Skip(1).Average():F0} ms");
+}
diff --git a/windows/spike/WinMLProbe/WinMLProbe.csproj b/windows/spike/WinMLProbe/WinMLProbe.csproj
new file mode 100644
index 0000000..7743f9a
--- /dev/null
+++ b/windows/spike/WinMLProbe/WinMLProbe.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <!-- Checks that Windows' built-in Windows ML runs the voiceprint model, and how fast. -->
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <SelfContained>true</SelfContained>
+ <PublishSingleFile>true</PublishSingleFile>
+ </PropertyGroup>
+</Project>
diff --git a/windows/spike/clips/three.txt b/windows/spike/clips/three.txt
new file mode 100644
index 0000000..d6aa3a7
--- /dev/null
+++ b/windows/spike/clips/three.txt
@@ -0,0 +1,18 @@
+Samantha|Good morning everyone, let's go through the launch plan for this quarter.
+Daniel|Thanks. The payment migration finished last Thursday, and the error rate is down to point three percent.
+Tingting|安卓版本还有一个闪退问题,主要出现在三星手机上。
+Samantha|How long do you think it will take to fix the crash on those phones?
+Daniel|If the fix is ready by Monday, testing can sign off by Wednesday afternoon.
+Tingting|我这边可以周一之前把修复版本发给测试同事。
+Samantha|Great. Then we keep the twenty first as the release date for now.
+Daniel|I will update the release notes and send them to the design team today.
+Tingting|另外,我们需要确认一下客服那边的培训时间。
+Samantha|Let's ask the support lead to join tomorrow's meeting for that.
+Daniel|Sounds good. I will also check the marketing timeline with their team.
+Tingting|好的,那我把测试计划更新以后发到群里。
+Samantha|One more thing, please keep an eye on the server costs this month.
+Daniel|The costs went up a little after the migration, but it should settle soon.
+Tingting|我们下周可以再看一下成本的数据。
+Samantha|Perfect, thank you all. Let's meet again on Friday.
+Daniel|Thanks everyone, see you on Friday.
+Tingting|好的,周五见,大家辛苦了。
diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.cs
index 5a2257f..1f38f57 100644
--- a/windows/src/Cicada.Core/ListenEngine.cs
+++ b/windows/src/Cicada.Core/ListenEngine.cs
@@ -23,6 +23,12 @@ public sealed class ListenEngine
Segmenter? segmenter;
readonly Dictionary<int, Heard?> done = [];
readonly Dictionary<int, Segment> segments = [];
+ // 说话人识别: voiceprints are made alongside Ming's reply (order doesn't matter there), and
+ // grouped in line order when the line is recorded (it does there).
+ readonly Dictionary<int, Task<float[]?>> prints = [];
+ VoiceClusterer clusterer = new();
+ /// Set by the app: the voiceprint model, or null where there is none (the Mac CLI, tests).
+ public IVoiceprint? Voiceprint { get; set; }
readonly List<Task> inFlight = [];
int nextToDeliver = 1, lineCount;
TranscriptLine? last;
@@ -63,7 +69,7 @@ public sealed class ListenEngine
SessionId = session.Id;
lock (gate)
{
- done.Clear(); segments.Clear(); inFlight.Clear();
+ done.Clear(); segments.Clear(); inFlight.Clear(); prints.Clear(); clusterer = new();
nextToDeliver = 1; lineCount = 0; last = null; lastEnd = 0;
hint = null; candidate = null; candidateVotes = 0; Problem = null;
}
@@ -124,7 +130,11 @@ public sealed class ListenEngine
{
var wav = Wav.Bytes(seg.Samples);
string? lang;
- lock (gate) { segments[seg.Index] = seg; lang = hint; }
+ lock (gate)
+ {
+ segments[seg.Index] = seg; lang = hint;
+ if (settings.SpeakerVoices && Voiceprint is { } vp) prints[seg.Index] = Task.Run(() => vp.Embed(seg.Samples));
+ }
Changed?.Invoke();
var task = Task.Run(async () =>
{
@@ -181,11 +191,22 @@ public sealed class ListenEngine
else { candidate = null; candidateVotes = 0; }
}
+ // Whose voice: a line with hardly a letter ("." from a breath) gets none.
+ int? voice = null;
+ Task<float[]?>? print;
+ lock (gate) { prints.Remove(seg.Index, out print); }
+ if (print is not null && heard.Original.Count(char.IsLetter) >= 2)
+ {
+ var v = print.Wait(3000) ? print.Result : null;
+ if (v is not null) lock (gate) voice = clusterer.Label(v, seg.Seconds);
+ }
+
TranscriptLine line;
bool joined = false;
lock (gate)
{
- if (last is not null && Continues(last, seg.Start - lastEnd, heard))
+ // Two voices never share a line, however the sentence was cut.
+ if (last is not null && Continues(last, seg.Start - lastEnd, heard) && (voice is null || last.Voice is null || voice == last.Voice))
{
last.Src = Join(last.Src, heard.Original, heard.Lang);
last.Dst = last.Dst is null || heard.Translation is null ? null : Join(last.Dst, heard.Translation, target);
@@ -197,7 +218,7 @@ public sealed class ListenEngine
line = new 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;
}
diff --git a/windows/src/Cicada.Core/Notes.cs b/windows/src/Cicada.Core/Notes.cs
index 8d71429..fef4fea 100644
--- a/windows/src/Cicada.Core/Notes.cs
+++ b/windows/src/Cicada.Core/Notes.cs
@@ -186,10 +186,12 @@ public sealed class NotesEngine
public static string Prompt(MeetingNotes notes, IReadOnlyList<TranscriptLine> lines, int from, string language, bool final)
{
+ var numbers = SpeakerLabels.Numbers(lines);
string Line(int i)
{
var l = lines[i];
- var who = l.Speaker == "me" ? "你" : "对方";
+ // As Notes.swift: 说话人N once voices are told apart, 未识别 for a voice not on show.
+ var who = l.Speaker == "me" ? "你" : numbers.TryGetValue(l.Id, out var n) ? $"说话人{n}" : numbers.Count == 0 ? "对方" : "未识别";
return $"[L{i + 1} {Languages.Clock(l.T)} {who}] {l.Src}";
}
var current = notes.IsEmpty ? "{}" : CompactJson(notes);
diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.cs
index fddd3e4..f5a48fa 100644
--- a/windows/src/Cicada.Core/SessionStore.cs
+++ b/windows/src/Cicada.Core/SessionStore.cs
@@ -161,9 +161,11 @@ public sealed class SessionStore
b.AppendLine(s.StartedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).AppendLine();
if (s.Notes is { IsEmpty: false } n) b.AppendLine($"## {Strings.L("纪要")}").AppendLine().Append(NotesBody(n));
b.AppendLine($"## {Strings.L("文字记录")}").AppendLine();
+ var numbers = SpeakerLabels.Numbers(s.Lines);
foreach (var l in s.Lines.OrderBy(x => x.T))
{
- b.AppendLine($"**{Languages.Clock(l.T)}**{(l.Speaker == "me" ? $" {Strings.L("你")}:" : "")} {l.Src} ");
+ var who = l.Speaker == "me" ? Strings.L("你") : numbers.TryGetValue(l.Id, out var num) ? Strings.LF("说话人 %lld", num) : null;
+ b.AppendLine($"**{Languages.Clock(l.T)}**{(who is null ? "" : $" {who}:")} {l.Src} ");
if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src) b.AppendLine($"{l.Dst}");
b.AppendLine();
}
diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.cs
index 671ea3f..3f39a17 100644
--- a/windows/src/Cicada.Core/Settings.cs
+++ b/windows/src/Cicada.Core/Settings.cs
@@ -20,6 +20,8 @@ public sealed class AppSettings
[JsonPropertyName("uiLanguage")] public string UiLanguage { get; set; } = "system";
/// 字幕文字大小, in px.
[JsonPropertyName("subtitleSize")] public int SubtitleSize { get; set; } = 24;
+ /// 说话人识别: tell the other side's voices apart (on by default, as on the Mac).
+ [JsonPropertyName("speakerVoices")] public bool SpeakerVoices { get; set; } = true;
/// 同声传译: hold right Ctrl to speak into the meeting in its language.
[JsonPropertyName("speak")] public bool Speak { get; set; }
/// 我说的语言: "system" or a source code.
diff --git a/windows/src/Cicada.Core/Strings.cs b/windows/src/Cicada.Core/Strings.cs
index 6f2f4e2..46b81c5 100644
--- a/windows/src/Cicada.Core/Strings.cs
+++ b/windows/src/Cicada.Core/Strings.cs
@@ -47,6 +47,12 @@ public static class Strings
b.Append(next < args.Length ? args[next++] : "");
i++;
}
+ // The Mac's integer placeholders (Swift interpolation of an Int becomes %lld).
+ else if (text[i] == '%' && i + 3 < text.Length && text.AsSpan(i + 1, 3) is "lld")
+ {
+ b.Append(next < args.Length ? args[next++] : "");
+ i += 3;
+ }
else if (text[i] == '%' && i + 2 < text.Length && char.IsDigit(text[i + 1]) && text[i + 2] == '$' && i + 3 < text.Length && text[i + 3] == '@')
{
int n = text[i + 1] - '1';
diff --git a/windows/src/Cicada.Core/Translator.cs b/windows/src/Cicada.Core/Translator.cs
index fc40cb1..91a5aea 100644
--- a/windows/src/Cicada.Core/Translator.cs
+++ b/windows/src/Cicada.Core/Translator.cs
@@ -9,17 +9,20 @@ public sealed record Heard(string Lang, string Original, string? Translation);
/// Apple translation. Listening sends each stretch of audio to Ming's audio model, which returns
/// the language, the original and the translation in one call (as the Mac's speak-back does).
/// Text translation is Ling first, then Google; Google is also the only one that sees drafts.
-public sealed class Translator(LingClient ling)
+public sealed class Translator(LingClient ling, HttpMessageHandler? google = null)
{
- static readonly HttpClient Http = MakeHttp();
+ static readonly HttpClient Shared = MakeHttp(null);
+ // Tests hand in their own handler, so they never reach the real Google.
+ readonly HttpClient Http = google is null ? Shared : MakeHttp(google);
DateTime googleBackoffUntil = DateTime.MinValue;
/// Names and terms the notes have settled on, e.g. "江充 (…; misheard as 江松)".
public Func<IReadOnlyList<string>> Glossary { get; set; } = () => [];
- static HttpClient MakeHttp()
+ static HttpClient MakeHttp(HttpMessageHandler? handler)
{
- var h = new HttpClient { Timeout = TimeSpan.FromSeconds(8) };
+ var h = handler is null ? new HttpClient() : new HttpClient(handler);
+ h.Timeout = TimeSpan.FromSeconds(8);
h.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada/1.1");
return h;
}
@@ -130,7 +133,7 @@ public sealed class Translator(LingClient ling)
sealed class GoogleException(int status) : Exception($"http{status}") { public int Status { get; } = status; }
- static async Task<string?> Google(string text, string source, string target)
+ async Task<string?> Google(string text, string source, string target)
{
var url = "https://translate.googleapis.com/translate_a/single?client=gtx"
+ $"&sl={Uri.EscapeDataString(source)}&tl={Uri.EscapeDataString(target)}&dt=t&q={Uri.EscapeDataString(text)}";
diff --git a/windows/src/Cicada.Core/Voices.cs b/windows/src/Cicada.Core/Voices.cs
new file mode 100644
index 0000000..5b2a146
--- /dev/null
+++ b/windows/src/Cicada.Core/Voices.cs
@@ -0,0 +1,191 @@
+namespace Cicada;
+
+/// 说话人识别: telling the other side's voices apart, as the Mac does (SpeakerID.swift). A line's
+/// audio becomes a voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0, compressed to int8 by
+/// scripts/compress-voiceprint.py), voiceprints are grouped as lines arrive, and a voice gets a
+/// number once it has said enough. Everything runs on this PC; only the numbers are stored.
+public interface IVoiceprint
+{
+ /// A unit-length voiceprint of 16 kHz mono audio, or null (too short, or no model).
+ float[]? Embed(short[] samples);
+}
+
+/// Kaldi log-mel filterbank, as `torchaudio.compliance.kaldi.fbank` computes it with the defaults the
+/// model was trained on: 16 kHz, 25 ms Povey windows every 10 ms, DC removed, pre-emphasis 0.97,
+/// 512-point power spectrum, 80 mel bins from 20 Hz to 8 kHz, natural log. Then, as in training,
+/// each bin's mean over the clip is taken away.
+public static class Fbank
+{
+ public const int Bins = 80, FrameLength = 400, Shift = 160, FftSize = 512;
+ public const double MinSeconds = 0.5, MaxSeconds = 20;
+
+ static readonly double[] window = Enumerable.Range(0, FrameLength).Select(i => Math.Pow(0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (FrameLength - 1)), 0.85)).ToArray();
+
+ // `Bins` rows of FftSize/2+1 weights (the Nyquist column is always zero, as in Kaldi).
+ static readonly double[,] banks = MakeBanks();
+
+ static double[,] MakeBanks()
+ {
+ static double Mel(double f) => 1127 * Math.Log(1 + f / 700);
+ int cols = FftSize / 2 + 1;
+ double lo = Mel(20), hi = Mel(8000), delta = (hi - lo) / (Bins + 1);
+ var w = new double[Bins, cols];
+ for (int m = 0; m < Bins; m++)
+ {
+ double left = lo + m * delta, center = left + delta, right = center + delta;
+ for (int k = 0; k < FftSize / 2; k++)
+ {
+ var x = Mel(k * 16000.0 / FftSize);
+ var v = Math.Min((x - left) / (center - left), (right - x) / (right - center));
+ if (v > 0) w[m, k] = v;
+ }
+ }
+ return w;
+ }
+
+ /// Frames × Bins, row-major, mean-normalised; null when too short for a voiceprint (0.5 s).
+ public static float[]? Features(short[] samples)
+ {
+ if (samples.Length < MinSeconds * 16000) return null;
+ int n = Math.Min(samples.Length, (int)(MaxSeconds * 16000));
+ int frames = 1 + (n - FrameLength) / Shift;
+ if (frames < 50) return null;
+ int cols = FftSize / 2 + 1;
+ var outp = new float[frames * Bins];
+ var re = new double[FftSize]; var im = new double[FftSize];
+ var power = new double[cols];
+ for (int f = 0; f < frames; f++)
+ {
+ int start = f * Shift;
+ double mean = 0;
+ for (int i = 0; i < FrameLength; i++) mean += samples[start + i];
+ mean /= FrameLength;
+ var frame = new double[FrameLength];
+ for (int i = 0; i < FrameLength; i++) frame[i] = samples[start + i] - mean;
+ for (int i = FrameLength - 1; i > 0; i--) frame[i] -= 0.97 * frame[i - 1];
+ frame[0] -= 0.97 * frame[0];
+ Array.Clear(im);
+ for (int i = 0; i < FftSize; i++) re[i] = i < FrameLength ? frame[i] * window[i] : 0;
+ Fft(re, im);
+ for (int k = 0; k < cols; k++) power[k] = re[k] * re[k] + im[k] * im[k];
+ for (int b = 0; b < Bins; b++)
+ {
+ double e = 0;
+ for (int k = 0; k < cols; k++) e += banks[b, k] * power[k];
+ outp[f * Bins + b] = (float)Math.Log(Math.Max(e, 1.1920929e-07 /* Float.ulpOfOne, as the Mac */));
+ }
+ }
+ for (int b = 0; b < Bins; b++)
+ {
+ double sum = 0;
+ for (int f = 0; f < frames; f++) sum += outp[f * Bins + b];
+ var m = (float)(sum / frames);
+ for (int f = 0; f < frames; f++) outp[f * Bins + b] -= m;
+ }
+ return outp;
+ }
+
+ /// In-place radix-2 FFT.
+ static void Fft(double[] re, double[] im)
+ {
+ int n = re.Length;
+ for (int i = 1, j = 0; i < n; i++)
+ {
+ int bit = n >> 1;
+ for (; (j & bit) != 0; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) { (re[i], re[j]) = (re[j], re[i]); (im[i], im[j]) = (im[j], im[i]); }
+ }
+ for (int len = 2; len <= n; len <<= 1)
+ {
+ double ang = -2 * Math.PI / len, wr = Math.Cos(ang), wi = Math.Sin(ang);
+ for (int i = 0; i < n; i += len)
+ {
+ double cr = 1, ci = 0;
+ for (int k = 0; k < len / 2; k++)
+ {
+ int a = i + k, b = a + len / 2;
+ double tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
+ re[b] = re[a] - tr; im[b] = im[a] - ti;
+ re[a] += tr; im[a] += ti;
+ (cr, ci) = (cr * wr - ci * wi, cr * wi + ci * wr);
+ }
+ }
+ }
+ }
+}
+
+/// 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 (对方). Tuned on AMI dev meetings (the Mac's VoiceClusterer).
+public sealed class VoiceClusterer
+{
+ public const double NewSeconds = 2.0;
+ public const float Join = 0.5f, StartNew = 0.5f;
+ readonly List<float[]> sums = [];
+
+ public int? Label(float[] v, double seconds)
+ {
+ int best = -1; float bestSim = -1;
+ for (int i = 0; i < sums.Count; i++)
+ {
+ float dot = 0, sq = 0;
+ for (int k = 0; k < v.Length; k++) { dot += v[k] * sums[i][k]; sq += sums[i][k] * sums[i][k]; }
+ var sim = dot / Math.Max(MathF.Sqrt(sq), float.Epsilon);
+ if (sim > bestSim) { bestSim = sim; best = i; }
+ }
+ if (best >= 0 && bestSim >= Join)
+ {
+ for (int k = 0; k < v.Length; k++) sums[best][k] += v[k];
+ return best;
+ }
+ if (seconds >= NewSeconds && (sums.Count == 0 || bestSim < StartNew))
+ {
+ sums.Add((float[])v.Clone());
+ return sums.Count - 1;
+ }
+ return null;
+ }
+}
+
+/// What the transcript shows for the other side's lines (the Mac's SpeakerLabels). A voice gets a
+/// number only once it has `ShownAfter` lines, and only when at least two voices have, so a
+/// one-to-one call stays 对方. Numbers follow the order voices got there, so a number never moves.
+public static class SpeakerLabels
+{
+ public const int ShownAfter = 5;
+
+ /// Long enough to say whose voice it is: three words, or four characters of CJK.
+ public static bool Substantive(string text)
+ {
+ var words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Count(w => w.Any(char.IsLetter));
+ if (words >= 3) return true;
+ return text.Count(c => c is >= '一' and <= '鿿' or >= '㐀' and <= '䶿' or >= '぀' and <= 'ヿ' or >= '가' and <= '힣') >= 4;
+ }
+
+ /// Voice id → 1-based speaker number, for the voices on show.
+ public static Dictionary<int, int> VoiceNumbers(IReadOnlyList<TranscriptLine> lines)
+ {
+ var count = new Dictionary<int, int>();
+ var reached = new Dictionary<int, int>();
+ for (int i = 0; i < lines.Count; i++)
+ {
+ var l = lines[i];
+ if (l.Speaker != "them" || l.Voice is not { } v || !Substantive(l.Src)) continue;
+ count[v] = count.GetValueOrDefault(v) + 1;
+ if (count[v] == ShownAfter) reached[v] = i;
+ }
+ if (reached.Count < 2) return [];
+ return reached.OrderBy(kv => kv.Value).Select((kv, n) => (kv.Key, n + 1)).ToDictionary(x => x.Key, x => x.Item2);
+ }
+
+ /// Line id → 1-based speaker number; lines without one show as 对方.
+ public static Dictionary<string, int> Numbers(IReadOnlyList<TranscriptLine> lines)
+ {
+ var number = VoiceNumbers(lines);
+ var outp = new Dictionary<string, int>();
+ foreach (var l in lines)
+ if (l.Speaker == "them" && l.Voice is { } v && number.TryGetValue(v, out var n)) outp[l.Id] = n;
+ return outp;
+ }
+}
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index 5f31e6e..639b71e 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -73,6 +73,7 @@ sealed class Controller
Speak = new SpeakEngine(Ling, Translator, Store, Settings, () => Listen.Spoken,
() => Listen.Listening && Listen.SessionId is { } id && Store.Get(id) is { } s ? (id, s.StartedAt) : null, WindowsVoice);
Speak.Changed += () => Dispatch.BeginInvoke(() => { speakBar ??= new SpeakBar(this); speakBar.Refresh(); });
+ Listen.Voiceprint = new WinVoiceprint();
Listen.Changed += Changed;
Notes.Changed += Changed;
Store.Changed += _ => Changed();
@@ -408,6 +409,8 @@ sealed class Controller
["showInCapture"] = Settings.ShowInCapture,
["sessions"] = Store.All().Count,
["hotkey"] = HotkeyRegistered,
+ ["speakerVoices"] = Settings.SpeakerVoices,
+ ["voices"] = Listen.SessionId is { } vid && Store.Get(vid) is { } vs ? string.Join(",", vs.Lines.Where(l => l.Speaker == "them").Select(l => SpeakerLabels.Numbers(vs.Lines).TryGetValue(l.Id, out var n) ? n.ToString() : l.Voice is { } v ? $"v{v}" : "-")) : "",
["speak"] = Settings.Speak,
["speakState"] = Speak.State.ToString(),
["speakTarget"] = Speak.Target,
@@ -480,6 +483,7 @@ static class DebugServer
if (arg == "on" || arg == "off") { app.Settings.Speak = arg == "on"; app.Settings.Save(); app.SettingsChanged(); }
else _ = app.Speak.Speak(Wav.Bytes(Wav.Read(arg)), new DeviceSpeaker(Endpoints.Cable));
break;
+ case "speakers": app.Settings.SpeakerVoices = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;
case "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;
case "record": _ = app.RecordCable(arg); break;
case "preview": _ = app.Preview(arg.Length > 0 ? arg : app.Speak.Target); break;
diff --git a/windows/src/Cicada/Assets/voiceprint.onnx b/windows/src/Cicada/Assets/voiceprint.onnx
new file mode 100644
index 0000000..8d1e97b
Binary files /dev/null and b/windows/src/Cicada/Assets/voiceprint.onnx differ
diff --git a/windows/src/Cicada/Cicada.csproj b/windows/src/Cicada/Cicada.csproj
index da81736..c47baf6 100644
--- a/windows/src/Cicada/Cicada.csproj
+++ b/windows/src/Cicada/Cicada.csproj
@@ -30,6 +30,9 @@
<None Include="Strings/**/Windows.strings" Link="Resources/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<!-- Both made by scripts/build.sh from docs/icon.png and Resources/sample/sample.m4a; committed so CI on Windows needs no Mac tools. -->
<Resource Include="Assets/cicada.ico" Link="cicada.ico" />
+ <!-- The voiceprint model (scripts/compress-voiceprint.py; WeSpeaker, CC BY 4.0), inside the exe so
+ single-file compression shrinks it too. -->
+ <EmbeddedResource Include="Assets/voiceprint.onnx" LogicalName="voiceprint.onnx" />
<None Include="Assets/sample.wav" Link="Resources/sample.wav" CopyToOutputDirectory="PreserveNewest" />
<ProjectReference Include="../Cicada.Core/Cicada.Core.csproj" />
</ItemGroup>
diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.cs
index e73b641..12409bf 100644
--- a/windows/src/Cicada/MainWindow.cs
+++ b/windows/src/Cicada/MainWindow.cs
@@ -279,9 +279,9 @@ sealed class MainWindow : Window
FrameworkElement? target = null;
// The line nearest the topic's time (older notes may hold a time no line has).
var nearest = jumpTo is { } t0 && s.Lines.Count > 0 ? s.Lines.MinBy(l => Math.Abs(l.T - t0)) : null;
- foreach (var l in s.Lines.OrderBy(x => x.T))
+ foreach (var (l, who, ink) in NotesWindow.Speakers(s.Lines, app.Settings.SpeakerVoices))
{
- var line = NotesWindow.TranscriptRow(l);
+ var line = NotesWindow.TranscriptRow(l, who, ink);
if (ReferenceEquals(l, nearest)) target = line;
body.Children.Add(line);
}
diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.cs
index 5d54777..e6597d1 100644
--- a/windows/src/Cicada/NotesWindow.cs
+++ b/windows/src/Cicada/NotesWindow.cs
@@ -244,8 +244,11 @@ sealed class NotesWindow : Window
}
else
{
- var who = line.Speaker == "me" ? L("你") : Ui.SpokenName(line.SrcLang);
- stack.Children.Add(Ui.Text($"{who} · {Languages.Clock(line.T)}", 12, line.Speaker == "me" ? Palette.AccentText : Palette.Tertiary, wrap: false));
+ var lines = app.Store.Get(listen.SessionId!)?.Lines ?? [];
+ var number = app.Settings.SpeakerVoices && line.Speaker == "them" && SpeakerLabels.Numbers(lines).TryGetValue(line.Id, out var n) ? n : (int?)null;
+ var who = line.Speaker == "me" ? L("你") : number is { } k ? $"{LF("说话人 %lld", k)} · {Ui.SpokenName(line.SrcLang)}" : Ui.SpokenName(line.SrcLang);
+ var whoInk = line.Speaker == "me" ? Palette.AccentText : number is { } k2 ? Palette.Speaker(k2) : Palette.Tertiary;
+ stack.Children.Add(Ui.Text($"{who} · {Languages.Clock(line.T)}", 12, whoInk, wrap: false));
if (line.Dst is not null && line.Dst != line.Src) stack.Children.Add(Gap(Ui.Text(line.Src, 13, Palette.Secondary), 4, top: true));
stack.Children.Add(Gap(Ui.Text(line.Dst ?? line.Src, 17, Palette.Ink, FontWeights.SemiBold), 2, top: true));
if (listen.Listening && listen.Pending > 0)
@@ -318,11 +321,32 @@ sealed class NotesWindow : Window
var body = new StackPanel();
// Stored as they arrive (the notes count them); shown in time order, so a sentence I said
// sits between the other side's, which come back from Ming a little later.
- foreach (var l in lines.OrderBy(x => x.T)) body.Children.Add(TranscriptRow(l));
+ foreach (var (l, who, ink) in Speakers(lines, app.Settings.SpeakerVoices)) body.Children.Add(TranscriptRow(l, who, ink));
return body;
}
- internal static FrameworkElement TranscriptRow(TranscriptLine l)
+ /// Lines in time order with who said them, named only where the speaker changes (as chat apps
+ /// do): 你 for what I said into the meeting, 说话人 N once voices are told apart.
+ internal static IEnumerable<(TranscriptLine line, string? who, Brush? ink)> Speakers(IReadOnlyList<TranscriptLine> lines, bool voices)
+ {
+ var numbers = voices ? SpeakerLabels.Numbers(lines) : [];
+ string? last = null;
+ foreach (var l in lines.OrderBy(x => x.T))
+ {
+ var key = l.Speaker == "me" ? "me" : numbers.TryGetValue(l.Id, out var n) ? $"n{n}" : "them";
+ string? who = null; Brush? ink = null;
+ if (key != last)
+ {
+ if (key == "me") { who = L("你"); ink = Palette.AccentText; }
+ else if (numbers.TryGetValue(l.Id, out var m)) { who = LF("说话人 %lld", m); ink = Palette.Speaker(m); }
+ else if (numbers.Count > 0) { who = L("未识别"); ink = Palette.Tertiary; }
+ }
+ last = key;
+ yield return (l, who, ink);
+ }
+ }
+
+ internal static FrameworkElement TranscriptRow(TranscriptLine l, string? who = null, Brush? ink = null)
{
var row = new DockPanel { Margin = new Thickness(0, 0, 0, 12) };
var time = Ui.Text(Languages.Clock(l.T), 12, Palette.AccentText, FontWeights.SemiBold, wrap: false);
@@ -330,8 +354,7 @@ sealed class NotesWindow : Window
DockPanel.SetDock(time, Dock.Left);
row.Children.Add(time);
var text = new StackPanel();
- // What I said into the meeting (同声传译) is marked, as the Mac names it 你.
- if (l.Speaker == "me") text.Children.Add(Ui.Text(L("你"), 12, Palette.AccentText, FontWeights.SemiBold, wrap: false));
+ if (who is not null) text.Children.Add(Ui.Text(who, 12, ink ?? Palette.Secondary, FontWeights.SemiBold, wrap: false));
text.Children.Add(Ui.Text(l.Src, 14, Palette.Ink));
if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src) text.Children.Add(Gap(Ui.Text(l.Dst, 13, Palette.Secondary), 2, top: true));
row.Children.Add(text);
diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.cs
index 2adacc8..1b94998 100644
--- a/windows/src/Cicada/SettingsWindow.cs
+++ b/windows/src/Cicada/SettingsWindow.cs
@@ -63,10 +63,11 @@ sealed class SettingsWindow : Window
Section(page, "speak", L("同声传译"), SpeakCards());
Section(page, "privacy", L("隐私与启动"), Group(
Card(Icons.Eye, L("共享屏幕时让对方看到"), L("关着时,截图和屏幕共享里看不到纪要和字幕"), Ui.Switch(app.Settings.ShowInCapture, app.SetShowInCapture, L("共享屏幕时让对方看到"))),
+ Card(Icons.List, L("说话人识别"), L("按声音标出说话人 1、2…,只在这台电脑上处理"), Ui.Switch(app.Settings.SpeakerVoices, v => { app.Settings.SpeakerVoices = v; Save(); }, L("说话人识别"))),
Card(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),
Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))));
var version = typeof(SettingsWindow).Assembly.GetName().Version?.ToString(3) ?? "";
- Section(page, "about", L("关于"), Group(Card(null, LF("知了 %@", version), null, Ui.LinkText(L("打开日志"), () => OpenFolder(Path.GetDirectoryName(Paths.Log)!)), AppIcon.Small(24))));
+ Section(page, "about", L("关于"), Group(Card(null, LF("知了 %@", version), L("说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)"), Ui.LinkText(L("打开日志"), () => OpenFolder(Path.GetDirectoryName(Paths.Log)!)), AppIcon.Small(24))));
scroll.Content = page;
scroll.ScrollToVerticalOffset(offset);
Nav();
diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.strings
index f59bd48..53761b2 100644
--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings
@@ -60,6 +60,7 @@
"打开设置" = "Settings";
"按住%@说话" = "Hold %@ to speak";
"按住%@说话,对方听到的是翻译后的声音" = "Hold %@ to speak. Others hear the translated voice.";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "Labels lines Speaker 1, 2… by voice, on this PC only";
"换成字幕条" = "Switch to subtitle bar";
"换成纪要" = "Switch to notes";
"换成耳机或蓝牙音箱也能接着听。" = "Keeps working when you switch to headphones or Bluetooth speakers.";
@@ -110,6 +111,7 @@
"设置知了" = "Set up Cicada";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "Cicada uses Ling for transcription, translation, and notes. Go to the Ling platform, select \"Create token\", and paste the key starting with sk- below.";
"试一下" = "Try it out";
+"说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)" = "Speaker identification uses the WeSpeaker voiceprint model (CC BY 4.0)";
"还没听到声音" = "No audio detected yet";
"还没填 key" = "No key added";
"还没接上 Ling" = "Not connected to Ling";
diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
index 0b00934..9f051e8 100644
--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
@@ -60,6 +60,7 @@
"打开设置" = "設定";
"按住%@说话" = "%@ を押しながら話す";
"按住%@说话,对方听到的是翻译后的声音" = "%@ を押しながら話すと、相手には翻訳された声が届きます";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "声で話者 1、2… を表示します。処理はこの PC の中だけです";
"换成字幕条" = "字幕バーに切り替え";
"换成纪要" = "メモに切り替え";
"换成耳机或蓝牙音箱也能接着听。" = "イヤホンや Bluetooth スピーカーに切り替えてもそのまま聞き取れます。";
@@ -110,6 +111,7 @@
"设置知了" = "Cicada のセットアップ";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "音声認識、翻訳、メモの作成には Ling を使用します。Ling プラットフォームで「トークンを作成」をクリックし、sk- で始まる文字列を下に貼り付けてください。";
"试一下" = "試してみる";
+"说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)" = "話者識別には WeSpeaker の声紋モデル(CC BY 4.0)を使っています";
"还没听到声音" = "まだ音声が聞こえません";
"还没填 key" = "キーが未入力です";
"还没接上 Ling" = "Ling に未接続";
diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
index 01208f5..38d674c 100644
--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
@@ -60,6 +60,7 @@
"打开设置" = "설정";
"按住%@说话" = "%@ 키를 누른 채 말하기";
"按住%@说话,对方听到的是翻译后的声音" = "%@ 키를 누른 채 말하면 상대방에게는 번역된 목소리가 들립니다";
+"按声音标出说话人 1、2…,只在这台电脑上处理" = "목소리로 화자 1, 2…를 표시해요. 이 PC에서만 처리해요";
"换成字幕条" = "자막 바로 전환";
"换成纪要" = "회의록으로 전환";
"换成耳机或蓝牙音箱也能接着听。" = "이어폰이나 블루투스 스피커로 바꿔도 계속 들을 수 있습니다.";
@@ -110,6 +111,7 @@
"设置知了" = "Cicada 설정";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "음성 인식, 번역, 회의록 작성에 모두 사용됩니다. Ling 오픈 플랫폼에서 '토큰 생성'을 클릭한 후, sk-로 시작하는 키를 복사해 아래에 붙여넣으세요.";
"试一下" = "테스트";
+"说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)" = "화자 인식에 WeSpeaker 성문 모델(CC BY 4.0)을 사용해요";
"还没听到声音" = "아직 소리가 감지되지 않음";
"还没填 key" = "아직 키를 입력하지 않음";
"还没接上 Ling" = "Ling에 연결되지 않음";
diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.cs
index b1944a1..1f2d753 100644
--- a/windows/src/Cicada/Ui.cs
+++ b/windows/src/Cicada/Ui.cs
@@ -39,6 +39,10 @@ static class Palette
public static readonly SolidColorBrush WarnIcon = B(0x9D5D00);
public static readonly SolidColorBrush Night = B(0x15171C);
public static readonly SolidColorBrush NightText = B(0xB4B9C2);
+ /// 说话人 1, 2, 3… cycling after four (the Mac's SpeakerColor): not the accent (live, and 你),
+ /// distinct in lightness, all ≥ 4.5:1 on white.
+ static readonly SolidColorBrush[] inks = [B(0x0F7B6C), B(0x7A4CC2), B(0xB03A7A), B(0x8A5A00)];
+ public static SolidColorBrush Speaker(int n) => inks[(Math.Max(1, n) - 1) % inks.Length];
public static readonly FontFamily Font = new("Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic");
}
diff --git a/windows/src/Cicada/WinVoiceprint.cs b/windows/src/Cicada/WinVoiceprint.cs
new file mode 100644
index 0000000..1fa992f
--- /dev/null
+++ b/windows/src/Cicada/WinVoiceprint.cs
@@ -0,0 +1,60 @@
+using Windows.AI.MachineLearning;
+
+namespace Cicada.App;
+
+/// The voiceprint model on Windows' built-in Windows ML (no runtime to ship). Loaded on first use
+/// from inside the exe; one inference at a time, about 0.15 s for a 5 s line.
+sealed class WinVoiceprint : IVoiceprint
+{
+ readonly object one = new();
+ LearningModelSession? session;
+ bool failed;
+
+ public float[]? Embed(short[] samples)
+ {
+ var feats = Fbank.Features(samples);
+ if (feats is null) return null;
+ lock (one)
+ {
+ if (session is null && !failed) Load();
+ if (session is null) return null;
+ try
+ {
+ var binding = new LearningModelBinding(session);
+ binding.Bind("feats", TensorFloat.CreateFromArray([1, feats.Length / Fbank.Bins, Fbank.Bins], feats));
+ var result = session.Evaluate(binding, "");
+ var v = ((TensorFloat)result.Outputs["embs"]).GetAsVectorView().ToArray();
+ var norm = MathF.Sqrt(v.Sum(x => x * x));
+ if (norm <= 0) return null;
+ for (int i = 0; i < v.Length; i++) v[i] /= norm;
+ return v;
+ }
+ catch (Exception e) { Log.Debug($"voiceprint: failed {e.GetType().Name}"); return null; }
+ }
+ }
+
+ void Load()
+ {
+ try
+ {
+ var started = DateTime.UtcNow;
+ using var res = typeof(WinVoiceprint).Assembly.GetManifestResourceStream("voiceprint.onnx") ?? throw new FileNotFoundException("voiceprint.onnx");
+ var bytes = new byte[res.Length];
+ res.ReadExactly(bytes);
+ // Written through a DataWriter: a .NET stream wrapper would close the WinRT stream with it.
+ var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
+ using (var w = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0)))
+ {
+ w.WriteBytes(bytes);
+ w.StoreAsync().AsTask().Wait();
+ w.FlushAsync().AsTask().Wait();
+ w.DetachStream();
+ }
+ stream.Seek(0);
+ var model = LearningModel.LoadFromStream(Windows.Storage.Streams.RandomAccessStreamReference.CreateFromStream(stream));
+ session = new LearningModelSession(model, new LearningModelDevice(LearningModelDeviceKind.Cpu));
+ Log.Debug($"voiceprint: model ready in {(DateTime.UtcNow - started).TotalMilliseconds:F0} ms");
+ }
+ catch (Exception e) { failed = true; Log.Debug($"voiceprint: model failed to load {e.GetType().Name}: {e.Message}"); }
+ }
+}
diff --git a/windows/tests/Cicada.Tests/Cicada.Tests.csproj b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
index 57cbf78..7c7b078 100644
--- a/windows/tests/Cicada.Tests/Cicada.Tests.csproj
+++ b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
@@ -8,6 +8,7 @@
<ItemGroup>
<None Include="../../../Resources/**/Localizable.strings" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />
<None Include="../../src/Cicada/Strings/**/Windows.strings" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />
+ <None Include="Fixtures/**" CopyToOutputDirectory="PreserveNewest" />
<ProjectReference Include="../../src/Cicada.Core/Cicada.Core.csproj" />
</ItemGroup>
</Project>
diff --git a/windows/tests/Cicada.Tests/Fixtures/fbank.json b/windows/tests/Cicada.Tests/Fixtures/fbank.json
new file mode 100644
index 0000000..90ea28f
--- /dev/null
+++ b/windows/tests/Cicada.Tests/Fixtures/fbank.json
@@ -0,0 +1 @@
+{"frames": 118, "rows": {"0": [1.4164, 1.4214, -0.0567, -0.0303, -0.0127, 0.0002, 0.0006, -0.0001, -0.0002, 0.0016, 0.0046, 0.009, 0.0132, 0.005, 0.0031, 0.0035, 0.0139, -0.2584, -0.1775, -0.2234, -0.6567, -0.6109, -0.5131, -0.3867, -0.3925, -0.384, -0.1014, -0.0944, -0.0657, -0.0158, -0.015, -0.0014, -0.0, -0.0, -0.0, 0.0002, 0.0003, 0.0043, 0.0091, 0.0104, 0.0214, 0.0327, 0.039, 0.0938, 0.2583, 0.652, 1.2596, 2.41, 3.2709, 4.2319, 5.8842, 8.3035, 13.062, 18.5599, 18.5326, 13.9072, 7.0456, 3.6898, 1.7096, 0.3606, -0.8943, -1.4171, -1.8405, -2.4654, -2.164, -3.2625, -3.4638, -3.4844, -3.1196, -3.0475, -2.9962, -2.358, -4.0451, -4.0318, -3.6199, -4.6527, -5.0513, -6.1437, -6.2181, -4.4347], "37": [0.6974, 0.4118, -0.1215, -0.0003, 0.0066, -0.0004, -0.0006, 0.0003, 0.0001, -0.0011, -0.0047, -0.0112, -0.0175, -0.0167, -0.0375, -0.0504, -0.0587, -0.0018, -0.0319, -0.0661, 0.1996, 0.4709, 0.3277, -0.0514, -0.0346, -0.0113, -0.0378, -0.018, -0.0312, -0.0059, -0.0034, -0.0007, -0.0001, -0.0, -0.0, 0.0, 0.0, 0.0024, 0.0072, 0.0064, 0.0201, 0.0367, 0.0017, 0.0487, 0.0669, 0.1362, -0.0105, -0.0374, -0.0402, 0.3601, 0.0502, -0.9097, -1.0869, -0.9674, -1.086, -1.9664, -1.221, -0.9914, -1.4875, -1.5639, -1.2313, -0.5874, 0.1205, 1.3497, 3.2916, 8.0584, 16.4492, 17.127, 11.4291, 3.7968, 1.0025, -0.8532, -2.1207, -2.8452, -2.8288, -3.8993, -5.6401, -5.9918, -5.9276, -5.1777], "117": [0.6811, 0.3982, -0.1205, -0.0002, 0.0066, -0.0004, -0.0006, 0.0003, 0.0, -0.0012, -0.0047, -0.0113, -0.0183, -0.0181, -0.036, -0.0468, -0.0751, -0.0033, -0.0276, -0.0646, 0.2494, 0.4167, 0.3777, 0.0272, -0.0322, -0.0377, -0.0476, -0.019, -0.0344, -0.0046, -0.0045, -0.0009, -0.0001, -0.0, -0.0, 0.0002, 0.0, 0.0019, -0.003, 0.0156, 0.0178, -0.0101, 0.0386, 0.0666, 0.1219, 0.194, -0.0387, 0.0427, -0.2789, -0.3191, -0.4849, -0.8733, -0.9704, -0.7016, -1.5868, -1.9386, -2.1303, -2.295, -2.5058, -2.8773, -3.6712, -3.3617, -2.7135, -1.9908, -3.373, -2.0505, -1.5463, -3.145, -2.6629, -2.0252, -1.9566, -0.973, 0.344, 2.8609, 11.8337, 15.4654, 12.9388, 1.5928, -2.0188, -3.0982]}}
\ No newline at end of file
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index 7aa546b..59c112b 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -409,6 +409,89 @@ static class Tests
finally { LingClient.Spacing = old; }
}
+ // MARK: Voices
+
+ public static void FbankMatchesKaldi()
+ {
+ var x = new short[19200];
+ for (int t = 0; t < x.Length; t++)
+ x[t] = (short)Math.Round(8000 * Math.Sin(2 * Math.PI * 220 * t / 16000) + 3000 * Math.Sin(2 * Math.PI * 1375 * t / 16000) + 1500 * Math.Sin(2 * Math.PI * 3100 * t / 16000 * (1 + t / 19200.0)));
+ var f = Fbank.Features(x)!;
+ var fx = JsonNode.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "fbank.json")))!;
+ Equal(fx["frames"]!.GetValue<int>() * Fbank.Bins, f.Length, "frame count");
+ foreach (var (row, values) in fx["rows"]!.AsObject())
+ {
+ int r = int.Parse(row);
+ var want = values!.AsArray().Select(v => v!.GetValue<double>()).ToArray();
+ var worst = Enumerable.Range(0, Fbank.Bins).Max(b => Math.Abs(f[r * Fbank.Bins + b] - want[b]));
+ Check(worst < 2e-3, $"row {r} off by {worst:F5} from numpy/Kaldi");
+ }
+ Check(Fbank.Features(new short[4000]) is null, "under 0.5 s gives no voiceprint");
+ }
+
+ static float[] Unit(params float[] v) { var n = MathF.Sqrt(v.Sum(x => x * x)); return v.Select(x => x / n).ToArray(); }
+
+ public static void ClustersVoicesAsTheMacDoes()
+ {
+ var c = new VoiceClusterer();
+ Check(c.Label(Unit(1, 0, 0), 1.0) is null, "a short first line starts no voice");
+ Equal(0, c.Label(Unit(1, 0, 0), 3.0), "a long one does");
+ Equal(0, c.Label(Unit(0.9f, 0.3f, 0), 1.0), "a similar line joins it, even short");
+ Equal(1, c.Label(Unit(0, 1, 0), 2.5), "a long unlike line is a new voice");
+ Check(c.Label(Unit(0, 0, 1), 1.0) is null, "a short unlike line stays 对方");
+ }
+
+ public static void NumbersVoicesOnceTwoHaveSaidEnough()
+ {
+ TranscriptLine L(int i, int? v, string text = "we should ship it") => new() { Id = $"h{i}", Speaker = "them", Src = text, Voice = v };
+ var lines = new List<TranscriptLine>();
+ for (int i = 0; i < 5; i++) lines.Add(L(i, 7));
+ Equal(0, SpeakerLabels.Numbers(lines).Count, "one voice alone: still 对方");
+ for (int i = 5; i < 9; i++) lines.Add(L(i, 3));
+ lines.Add(L(9, 3, "yeah"));
+ Equal(0, SpeakerLabels.Numbers(lines).Count, "\"yeah\" doesn't count towards a name");
+ lines.Add(L(10, 3, "我们下周一定上线"));
+ var n = SpeakerLabels.Numbers(lines);
+ Check(n["h0"] == 1 && n["h10"] == 2 && !n.ContainsKey("h20"), "numbers in the order voices got there");
+ }
+
+ sealed class FakePrint(Func<short[], float[]?> f) : IVoiceprint { public float[]? Embed(short[] s) => f(s); }
+
+ public static async Task NeverJoinsTwoVoices()
+ {
+ // Two halves of one "sentence" (no full stop, 0.4 s apart) in two different voices.
+ var fake = new Fake(body =>
+ {
+ if (!body.Contains("Ming-3.0-audio-flash")) return Reply("{}");
+ var url = JsonNode.Parse(body)!["messages"]![1]!["content"]![0]!["audio_url"]!["url"]!.GetValue<string>();
+ return Reply(url.Length < 110_000 ? "LANG: en\nORIGINAL: so what we need\nTRANSLATION: 所以我们需要" : "LANG: en\nORIGINAL: is a plan for Monday\nTRANSLATION: 周一的计划");
+ });
+ var old = LingClient.Spacing; LingClient.Spacing = 0.05;
+ try
+ {
+ var ling = Client(fake);
+ var store = new SessionStore();
+ var engine = new ListenEngine(ling, new Translator(ling), store, new NotesEngine(ling, store), new AppSettings { Target = "zh-CN" })
+ {
+ // Told apart by length: the first stretch is 2.5 s, the second 3 s.
+ Voiceprint = new FakePrint(s => s.Length < 50_000 ? Unit(1, 0, 0) : Unit(0, 1, 0)),
+ };
+ var path = Path.Combine(Path.GetTempPath(), $"cicada-voices-{Environment.ProcessId}.wav");
+ File.WriteAllBytes(path, Wav.Bytes([.. Tone(2.5), .. Silence(0.7), .. Tone(3), .. Silence(1)]));
+ var src = new FileAudioSource(path, speed: 0);
+ var ended = new TaskCompletionSource();
+ src.Ended += _ => ended.TrySetResult();
+ engine.Start(src);
+ await ended.Task;
+ await Task.Delay(100);
+ await engine.Stop();
+ var lines = store.All().First().Lines;
+ Equal(2, lines.Count, "two voices, two lines (not joined)");
+ Check(lines[0].Voice == 0 && lines[1].Voice == 1, "each with its voice");
+ }
+ finally { LingClient.Spacing = old; }
+ }
+
// MARK: Speaking
sealed class Sink : ISpeechSink
@@ -451,7 +534,7 @@ static class Tests
}
static SpeakEngine Speaker(LingClient ling, NoVoice voice, AppSettings? settings = null) =>
- new(ling, new Translator(ling), new SessionStore(), settings ?? new AppSettings(), () => "en", () => null, voice);
+ new(ling, new Translator(ling, new Fake(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable))), new SessionStore(), settings ?? new AppSettings(), () => "en", () => null, voice);
public static async Task SpeaksTheTranslationNeverTheOriginal()
{
diff --git a/windows/vm/deploy.sh b/windows/vm/deploy.sh
index b269b70..26a2224 100755
--- a/windows/vm/deploy.sh
+++ b/windows/vm/deploy.sh
@@ -2,7 +2,7 @@
# Quits Cicada in the test VM and copies in fresh builds (run scripts/build.sh first).
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
-"$here/vmctl.sh" ssh 'Get-Process Cicada -ErrorAction SilentlyContinue | Stop-Process -Force; Start-Sleep 1; Remove-Item C:\cicada-test\Cicada-win-arm64, C:\cicada-test\Cicada-win-x64 -Recurse -Force -ErrorAction SilentlyContinue'
+"$here/vmctl.sh" ssh 'Get-Process Cicada -ErrorAction SilentlyContinue | Stop-Process -Force; Start-Sleep 1; Remove-Item C:\cicada-test\Cicada-win-arm64, C:\cicada-test\Cicada-win-x64 -Recurse -Force -ErrorAction SilentlyContinue; exit 0'
for rid in win-arm64 win-x64; do "$here/vmctl.sh" put "$here/../build/Cicada-$rid" C:/cicada-test/; done
"$here/vmctl.sh" put "$here/guest.ps1" C:/cicada-test/
echo deployed