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.

refactor: split the Mac engines from their AppKit views so the iOS app can compile them

wqugurube989e3182b6
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index aad34a6..3314d82 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -1192,7 +1192,7 @@ final class AppModel: ObservableObject {
if notesToo { notes.generate(for: id) }
let content = UNMutableNotificationContent()
content.title = L("\(s.displayTitle) 转好了")
- content.body = L("\(MainWindowView.length(s)) · \(s.lines.count) 句") + (notesToo ? L(",正在整理纪要") : "")
+ content.body = L("\(RecordList.length(s)) · \(s.lines.count) 句") + (notesToo ? L(",正在整理纪要") : "")
content.userInfo = ["session": id]
UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "import-\(id)", content: content, trigger: nil)) { error in
if let error { debugLog("import: notification not shown: \(error)") }
diff --git a/Sources/LiveSubs/AudioFiles.swift b/Sources/LiveSubs/AudioFiles.swift
new file mode 100644
index 0000000..f73b508
--- /dev/null
+++ b/Sources/LiveSubs/AudioFiles.swift
@@ -0,0 +1,72 @@
+import AVFoundation
+
+// Audio formats and files shared by the Mac and iOS apps (ios/shared-sources.txt).
+
+/// Stateful sample-rate / sample-format converter.
+final class PCMConverter {
+ private var converter: AVAudioConverter?
+
+ func convert(_ input: AVAudioPCMBuffer, to format: AVAudioFormat) -> AVAudioPCMBuffer? {
+ if input.format == format { return input }
+ if converter == nil || converter!.inputFormat != input.format || converter!.outputFormat != format {
+ converter = AVAudioConverter(from: input.format, to: format)
+ }
+ guard let converter else { return nil }
+ let ratio = format.sampleRate / input.format.sampleRate
+ let capacity = AVAudioFrameCount(Double(input.frameLength) * ratio) + 64
+ guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return nil }
+ var consumed = false
+ var error: NSError?
+ let status = converter.convert(to: out, error: &error) { _, outStatus in
+ if consumed {
+ outStatus.pointee = .noDataNow
+ return nil
+ }
+ consumed = true
+ outStatus.pointee = .haveData
+ return input
+ }
+ if status == .error || out.frameLength == 0 { return nil }
+ return out
+ }
+}
+
+enum AudioFileWriter {
+ /// AAC .m4a, mono, at the buffer's sample rate. The processing format must
+ /// match the buffers written to it exactly.
+ static func open(_ url: URL, format: AVAudioFormat) -> AVAudioFile? {
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let settings: [String: Any] = [
+ AVFormatIDKey: kAudioFormatMPEG4AAC,
+ AVSampleRateKey: format.sampleRate,
+ AVNumberOfChannelsKey: Int(format.channelCount),
+ AVEncoderBitRateKey: 32_000,
+ ]
+ return try? AVAudioFile(forWriting: url, settings: settings,
+ commonFormat: format.commonFormat, interleaved: format.isInterleaved)
+ }
+
+ /// Meetings are recorded as ADTS (`system.aac`), which stays readable up to the last packet
+ /// if the app is killed; an .m4a is unreadable until it is closed. `finish` turns it into
+ /// the .m4a afterwards (and at launch, for a meeting the app didn't get to close).
+ static func partial(_ url: URL) -> URL { url.deletingPathExtension().appendingPathExtension("aac") }
+
+ /// Rewraps `partial(url)` into `url` without re-encoding, then removes the partial file.
+ /// A partial file next to an .m4a means the last rewrap was cut short: it is done again.
+ /// `until`: seconds to keep from the start (the silent tail of a meeting that ended by itself).
+ nonisolated static func finish(_ url: URL, until: Double? = nil) async {
+ let src = partial(url)
+ guard FileManager.default.fileExists(atPath: src.path) else { return }
+ try? FileManager.default.removeItem(at: url)
+ let asset = AVURLAsset(url: src)
+ guard let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else { return }
+ if let until { export.timeRange = CMTimeRange(start: .zero, duration: CMTime(seconds: until, preferredTimescale: 600)) }
+ do {
+ try await export.export(to: url, as: .m4a)
+ try? FileManager.default.removeItem(at: src)
+ } catch {
+ debugLog("audio rewrap failed \(url.lastPathComponent): \(error)")
+ try? FileManager.default.removeItem(at: url)
+ }
+ }
+}
diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swift
index ae6cf80..0ec1c94 100644
--- a/Sources/LiveSubs/AudioRouter.swift
+++ b/Sources/LiveSubs/AudioRouter.swift
@@ -6,35 +6,6 @@ import CoreMedia
// MARK: - Audio routing
-/// Stateful sample-rate / sample-format converter.
-final class PCMConverter {
- private var converter: AVAudioConverter?
-
- func convert(_ input: AVAudioPCMBuffer, to format: AVAudioFormat) -> AVAudioPCMBuffer? {
- if input.format == format { return input }
- if converter == nil || converter!.inputFormat != input.format || converter!.outputFormat != format {
- converter = AVAudioConverter(from: input.format, to: format)
- }
- guard let converter else { return nil }
- let ratio = format.sampleRate / input.format.sampleRate
- let capacity = AVAudioFrameCount(Double(input.frameLength) * ratio) + 64
- guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return nil }
- var consumed = false
- var error: NSError?
- let status = converter.convert(to: out, error: &error) { _, outStatus in
- if consumed {
- outStatus.pointee = .noDataNow
- return nil
- }
- consumed = true
- outStatus.pointee = .haveData
- return input
- }
- if status == .error || out.frameLength == 0 { return nil }
- return out
- }
-}
-
/// Moves audio off the real-time thread, converts it for the analyzer,
/// feeds the live transcriber, and keeps a short ring buffer for language detection.
final class AudioRouter: @unchecked Sendable {
@@ -183,7 +154,8 @@ final class AudioRouter: @unchecked Sendable {
func fedSeconds() -> Double { queue.sync { fed } }
/// Analyzer clock now, the silence running at the end of it, and the last pause before that.
func clock() -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) {
- queue.sync { (fed: fed, silence: silenceRun, pause: pause) }
+ // The return type spelled out: Swift 6.4 (Xcode 27) crashes inferring this labelled tuple.
+ queue.sync { () -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) in (fed, silenceRun, pause) }
}
func attach(_ stream: RecognitionStream, replaySeconds: Double = 0) {
@@ -274,44 +246,3 @@ final class AudioRouter: @unchecked Sendable {
}
}
}
-
-
-enum AudioFileWriter {
- /// AAC .m4a, mono, at the buffer's sample rate. The processing format must
- /// match the buffers written to it exactly.
- static func open(_ url: URL, format: AVAudioFormat) -> AVAudioFile? {
- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- let settings: [String: Any] = [
- AVFormatIDKey: kAudioFormatMPEG4AAC,
- AVSampleRateKey: format.sampleRate,
- AVNumberOfChannelsKey: Int(format.channelCount),
- AVEncoderBitRateKey: 32_000,
- ]
- return try? AVAudioFile(forWriting: url, settings: settings,
- commonFormat: format.commonFormat, interleaved: format.isInterleaved)
- }
-
- /// Meetings are recorded as ADTS (`system.aac`), which stays readable up to the last packet
- /// if the app is killed; an .m4a is unreadable until it is closed. `finish` turns it into
- /// the .m4a afterwards (and at launch, for a meeting the app didn't get to close).
- static func partial(_ url: URL) -> URL { url.deletingPathExtension().appendingPathExtension("aac") }
-
- /// Rewraps `partial(url)` into `url` without re-encoding, then removes the partial file.
- /// A partial file next to an .m4a means the last rewrap was cut short: it is done again.
- /// `until`: seconds to keep from the start (the silent tail of a meeting that ended by itself).
- nonisolated static func finish(_ url: URL, until: Double? = nil) async {
- let src = partial(url)
- guard FileManager.default.fileExists(atPath: src.path) else { return }
- try? FileManager.default.removeItem(at: url)
- let asset = AVURLAsset(url: src)
- guard let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else { return }
- if let until { export.timeRange = CMTimeRange(start: .zero, duration: CMTime(seconds: until, preferredTimescale: 600)) }
- do {
- try await export.export(to: url, as: .m4a)
- try? FileManager.default.removeItem(at: src)
- } catch {
- debugLog("audio rewrap failed \(url.lastPathComponent): \(error)")
- try? FileManager.default.removeItem(at: url)
- }
- }
-}
diff --git a/Sources/LiveSubs/Diagnostics.swift b/Sources/LiveSubs/Diagnostics.swift
index aa56e2d..ce0b986 100644
--- a/Sources/LiveSubs/Diagnostics.swift
+++ b/Sources/LiveSubs/Diagnostics.swift
@@ -1,5 +1,5 @@
-import AppKit
-import SwiftUI
+import Combine
+import Foundation
// MARK: - Records
@@ -267,388 +267,3 @@ final class Diagnostics: ObservableObject {
return lines.joined(separator: "\n")
}
}
-
-// MARK: - View (settings › 诊断)
-
-struct DiagnosticsView: View {
- @ObservedObject var diagnostics: Diagnostics
- /// The service in settings: names the group, and the empty page before any request.
- var service: AIConfig
- @State private var copied = false
- @State private var tick = Date()
- private let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
-
- var body: some View {
- VStack(alignment: .leading, spacing: 14) {
- Text(subtitle).font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.top, -8)
- if empty {
- // Nothing measured yet: four dashes, a grey bar and zeros read as broken. Show
- // what each stage is and the shape a sentence will take instead.
- pipeline
- emptyChannels
- emptyRecent
- } else {
- // What people feel; each step's time is in the list below.
- HStack(spacing: 8) {
- tile(L("对方说完 → 你看到字幕"), diagnostics.endToEnd, dark: true)
- tile(L("你说完 → 对方听到"), diagnostics.toRoom)
- }
- uses
- totals
- recent
- }
- HStack(spacing: 8) {
- SoftButton(copied ? L("已复制") : L("复制诊断信息"), dark: !empty) { copy() }
- .disabled(empty)
- // The meeting folder holds metrics.jsonl; the log only exists in dev builds or with `debug` on.
- SoftButton(diagnostics.folder() == nil ? L("打开日志") : L("打开本场数据")) {
- NSWorkspace.shared.open(diagnostics.folder() ?? URL(fileURLWithPath: DevBuild.logPath))
- }
- Spacer()
- Text("只记时间和次数,不存字幕原文").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
- }
- }
- .onReceive(timer) { tick = $0 }
- }
-
- private var empty: Bool { diagnostics.sentences.isEmpty && diagnostics.calls.isEmpty }
-
- private var subtitle: String {
- guard let s = diagnostics.startedAt else { return L("开始聆听后,这里会显示每句话的耗时明细") }
- if empty { return L("有人说话后,这里会显示每句话的耗时明细") }
- let m = Int((diagnostics.endedAt ?? tick).timeIntervalSince(s) / 60)
- return L("这场会议 · \(m) 分钟 · \(diagnostics.heard.count) 句 · 同声传译 \(diagnostics.said.count) 次")
- }
-
- private func tile(_ title: String, _ s: Diagnostics.Stat?, dark: Bool = false) -> some View {
- VStack(alignment: .leading, spacing: 4) {
- Text(title).font(.system(size: 11)).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.secondary)
- Text(s.map { String(format: "%.1fs", $0.p50) } ?? "—").font(.system(size: 20, weight: .bold).monospacedDigit())
- .foregroundStyle(dark ? Color.white : Palette.ink)
- Text(s.map { String(format: "p95 %.1fs · %d", $0.p95, $0.n) } ?? L("暂无数据"))
- .font(.system(size: 11).monospacedDigit()).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.tertiary)
- }
- .padding(12).frame(maxWidth: .infinity, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 12).fill(dark ? Palette.ink : Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(dark ? .clear : Palette.line, lineWidth: 1))
- }
-
- // MARK: Before any sentence
-
- private var pipeline: some View {
- VStack(alignment: .leading, spacing: 16) {
- HStack {
- Text("一句话的路").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
- Spacer()
- Text("还没有句子").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
- }
- TimelineView(.animation(minimumInterval: 1 / 30)) { ctx in
- GeometryReader { g in
- ZStack(alignment: .leading) {
- Capsule().fill(Palette.fill).frame(height: 4)
- Circle().fill(Palette.accent).frame(width: 10, height: 10)
- .offset(x: phase(ctx.date, period: 2.4) * (g.size.width - 10))
- }
- .frame(maxHeight: .infinity)
- }
- }
- .frame(height: 10).padding(.horizontal, 14).accessibilityHidden(true)
- HStack(alignment: .top, spacing: 8) {
- stage(L("识别定稿"), L("听清这句话"))
- stage(L("翻译"), L("译成目标语言"))
- stage(L("说完到上屏"), L("你感到的延迟"))
- stage(L("纪要一轮"), L("更新一次纪要"))
- }
- }
- .padding(16)
- .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
- }
-
- private func stage(_ title: String, _ detail: String) -> some View {
- VStack(alignment: .leading, spacing: 4) {
- Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(2)
- .fixedSize(horizontal: false, vertical: true)
- Text(detail).font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(2)
- .fixedSize(horizontal: false, vertical: true)
- Text("– s").font(.system(size: 18, weight: .bold).monospacedDigit()).foregroundStyle(Palette.placeholder)
- }
- .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 4)
- }
-
- private var emptyChannels: some View {
- SettingsCard {
- SettingsRow(title: L("AI 服务"), detail: service.provider.id == .ling ? L("账号上限约每秒 2 次") : nil) {
- Text("\(service.provider.name) · \(Self.short(service.textModel))").font(.system(size: 12))
- .foregroundStyle(Palette.secondary).lineLimit(1)
- }
- SettingsRow(title: L("本场用量"), divider: false) {
- Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
- }
- }
- }
-
- private var emptyRecent: some View {
- VStack(alignment: .leading, spacing: 12) {
- Text("最近的句子").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
- HStack(spacing: 10) {
- Text("示例 · 对方").font(.system(size: 12)).foregroundStyle(Palette.tertiary).frame(width: 150, alignment: .leading)
- HStack(spacing: 1) {
- RoundedRectangle(cornerRadius: 2).fill(Color(red: 0.42, green: 0.44, blue: 0.50)).frame(width: 70)
- RoundedRectangle(cornerRadius: 2).fill(Color(red: 0.96, green: 0.78, blue: 0.71)).frame(width: 18)
- RoundedRectangle(cornerRadius: 2).fill(Palette.ink).frame(width: 46)
- }
- .frame(height: 10)
- Spacer(minLength: 0)
- Text("2.4s").font(.system(size: 12, weight: .semibold).monospacedDigit())
- }
- .opacity(0.5)
- HStack(spacing: 14) {
- legend(Color(red: 0.42, green: 0.44, blue: 0.50), L("识别"))
- legend(Color(red: 0.96, green: 0.78, blue: 0.71), L("排队"))
- legend(Palette.ink, L("翻译"))
- }
- }
- .padding(14)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
- }
-
- private func legend(_ color: Color, _ title: String) -> some View {
- HStack(spacing: 5) {
- RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 8, height: 8)
- Text(title).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
- }
- }
-
- /// The service's own ids (ling, zenmux…), as recorded in `via` and the fallbacks.
- private static func serviceName(_ id: String) -> String? { AIProvider.all.first { $0.id.rawValue == id }?.name }
-
- private static func color(_ via: String) -> Color {
- switch via {
- case "google": Palette.accent
- case "ming": Palette.accentInk
- default: serviceName(via) != nil ? Palette.ink : Color(red: 0.72, green: 0.74, blue: 0.78)
- }
- }
-
- private static func name(_ via: String) -> String {
- switch via {
- case "google": "Google"
- case "apple": L("本机")
- case "ming": L("Ming 语音")
- default: serviceName(via) ?? L("没译出")
- }
- }
-
- private static func reason(_ key: String) -> String {
- let parts = key.split(separator: ":").map(String.init)
- let who = parts.count < 2 ? "" : parts.first.map { $0 == "google" ? "Google" : $0 == "notes" ? L("纪要") : $0 == "ming" ? L("Ming 语音") : serviceName($0) ?? L("本机") } ?? ""
- let why: String
- switch parts.last ?? "" {
- case "hijacked": why = L("被搜索劫持")
- case "rateLimited", "429": why = L("限流")
- case "timeout": why = L("超时")
- case "unparsed": why = L("回复格式不对")
- case "network": why = L("网络错误")
- case "unavailable": why = L("未安装语言包")
- default: why = parts.last ?? ""
- }
- return who.isEmpty ? why : "\(who) \(why)"
- }
-
- /// "inclusionai/ling-3.0-flash" → "ling-3.0-flash": the vendor is in the group name already.
- static func short(_ model: String) -> String { model.split(separator: "/").last.map(String.init) ?? model }
-
- private static func seconds(_ x: Double) -> String { String(format: "%.1fs", x) }
-
- private static func count(_ n: Int) -> String { n >= 1000 ? String(format: "%.1fk", Double(n) / 1000) : "\(n)" }
-
- private static func title(_ role: String) -> String {
- switch role {
- case "translate": L("整句翻译")
- case "heard-me": L("听懂你说的")
- case "voice": L("同传声音")
- case "notes": L("实时纪要")
- case "speakers": L("认出说话人")
- default: role
- }
- }
-
- /// 1A: one row per use, a single big number (p50) with p95 under it. Uses that follow the AI
- /// service come first; the ones fixed on this Mac or Google come after, so switching service
- /// visibly changes only the first group.
- private var uses: some View {
- let uses = diagnostics.uses
- let retreats = diagnostics.retreats
- let current = service.provider.id.rawValue
- return VStack(alignment: .leading, spacing: 0) {
- group(L("跟着 AI 服务走 · \(service.provider.name)"))
- if uses.isEmpty {
- Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary).padding(.vertical, 9)
- }
- ForEach(Array(uses.enumerated()), id: \.element.id) { i, u in
- let model = (u.provider == current ? "" : (Self.serviceName(u.provider) ?? u.provider) + " · ") + Self.short(u.model)
- var foot = [L("\(u.n) 次")]
- if u.tokens > 0 { foot.append("\(Self.count(u.tokens)) token") }
- if u.chars > 0 { foot.append(L("\(u.chars) 字")) }
- var pill: String?
- let why = u.reasons.prefix(2).map { "\(Self.reason($0.0)) \($0.1)" }.joined(separator: "、")
- if u.role == "translate", let top = retreats.first {
- let n = retreats.reduce(0) { $0 + $1.1 }
- pill = L("\(n) 句退回 \(Self.name(top.0))") + (why.isEmpty ? "" : " · " + why)
- } else if u.failed > 0 {
- pill = L("失败 \(u.failed)") + (why.isEmpty ? "" : " · " + why)
- } else {
- foot.append(L("没有失败"))
- }
- return useRow(Self.title(u.role), u.role == "voice" ? model + " · " + L("到开始出声") : model,
- u.latency, foot: foot, pill: pill, divider: i > 0)
- }
- let fixed = fixedRows
- if !fixed.isEmpty {
- group(L("不受换服务影响")).padding(.top, 12)
- ForEach(Array(fixed.enumerated()), id: \.offset) { i, r in
- useRow(r.title, r.detail, r.stat, foot: r.foot, dim: true, divider: i > 0)
- }
- }
- }
- .padding(14)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
- }
-
- private var fixedRows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] {
- var rows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] = []
- if let r = diagnostics.recognize { rows.append((L("识别对方"), L("本机识别"), r, [L("\(r.n) 句")])) }
- if let r = diagnostics.recognizeMine { rows.append((L("识别你说的"), L("本机识别"), r, [L("\(r.n) 句")])) }
- let d = diagnostics.drafts
- if d.n > 0 {
- rows.append((L("半句翻译"), "Google", diagnostics.draftStat,
- [L("\(d.n) 次"), d.failed > 0 ? L("失败 \(d.failed)") : L("没有失败")]))
- }
- return rows
- }
-
- private func group(_ title: String) -> some View {
- Text(title).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.tertiary).padding(.bottom, 2)
- }
-
- private func useRow(_ title: String, _ detail: String, _ s: Diagnostics.Stat?, foot: [String] = [], pill: String? = nil,
- dim: Bool = false, divider: Bool) -> some View {
- VStack(alignment: .leading, spacing: 4) {
- HStack(alignment: .top, spacing: 12) {
- VStack(alignment: .leading, spacing: 2) {
- Text(title).font(.system(size: 13, weight: dim ? .medium : .semibold)).foregroundStyle(Palette.ink)
- Text(detail).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)
- }
- Spacer(minLength: 0)
- VStack(alignment: .trailing, spacing: 1) {
- Text(s.map { Self.seconds($0.p50) } ?? "—")
- .font(.system(size: dim ? 15 : 18, weight: .bold).monospacedDigit()).foregroundStyle(Palette.ink)
- if let s { Text("p95 " + Self.seconds(s.p95)).font(.system(size: 10).monospacedDigit()).foregroundStyle(Palette.tertiary) }
- }
- }
- if pill != nil || !foot.isEmpty {
- HStack(spacing: 6) {
- if let pill {
- Text(pill).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Palette.accentInk).lineLimit(1)
- .padding(.horizontal, 7).padding(.vertical, 1.5)
- .background(Capsule().fill(Palette.accentPale))
- }
- Text(foot.joined(separator: " · ")).font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.tertiary)
- .lineLimit(1)
- }
- }
- }
- .padding(.vertical, 9)
- .frame(maxWidth: .infinity, alignment: .leading)
- .overlay(alignment: .top) { if divider { Rectangle().fill(Palette.line).frame(height: 1) } }
- }
-
- private var totals: some View {
- let _ = tick
- let t = diagnostics.tokens
- let n = diagnostics.calls.count
- let chars = diagnostics.voiceChars
- return SettingsCard {
- if service.provider.id == .ling {
- SettingsRow(title: L("Ling 请求速度"), detail: L("账号上限约每秒 2 次")) {
- Text(String(format: L("%.1f / 2 次每秒"), diagnostics.lingRate)).font(.system(size: 12).monospacedDigit())
- .foregroundStyle(Palette.secondary)
- }
- }
- SettingsRow(title: L("排队最久"), detail: L("请求太密时,纪要让翻译先走")) {
- Text(String(format: "%.1fs", diagnostics.maxQueue)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)
- }
- SettingsRow(title: L("本场用量"), detail: L("服务返回的数,以服务的账单为准"), divider: false) {
- Text(chars > 0 ? L("\(n) 次 · \(t.0 + t.1) token · \(chars) 字语音") : L("\(n) 次 · \(t.0 + t.1) token"))
- .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)
- }
- }
- }
-
- /// The last few sentences as stacked bars: recognise · queue · translate (· voice).
- private var recent: some View {
- let rows = Array(diagnostics.sentences.suffix(6).reversed())
- return VStack(alignment: .leading, spacing: 0) {
- Text("最近的句子").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).padding(.bottom, 8)
- if rows.isEmpty {
- Text("还没有").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
- }
- ForEach(rows) { s in
- HStack(spacing: 10) {
- VStack(alignment: .leading, spacing: 1) {
- Text("\(Self.clock.string(from: s.at)) \(s.side == "me" ? L("你") : L("对方"))").font(.system(size: 12).monospacedDigit())
- Text(s.fallbacks.isEmpty ? L("\(Self.name(s.via)) · \(s.chars) 字") : s.fallbacks.map(Self.reason).joined(separator: "、") + " → " + Self.name(s.via))
- .font(.system(size: 10)).foregroundStyle(s.fallbacks.isEmpty ? Palette.tertiary : Palette.accentInk).lineLimit(1)
- }
- .frame(width: 150, alignment: .leading)
- bar(s)
- Spacer(minLength: 0)
- Text(String(format: "%.1fs", s.total + (s.firstAudio ?? s.voice ?? 0))).font(.system(size: 12, weight: .semibold).monospacedDigit())
- }
- .frame(height: 34)
- }
- }
- .padding(14)
- .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
- }
-
- private func bar(_ s: SentenceTiming) -> some View {
- let scale: CGFloat = 50 // points per second; 4 s ≈ 200 pt
- let fallback = s.failed
- return HStack(spacing: 1) {
- if let r = s.recognize { seg(r, Color(red: 0.42, green: 0.44, blue: 0.50), scale) }
- if s.queue > 0.05 { seg(s.queue, Color(red: 0.96, green: 0.78, blue: 0.71), scale) }
- if fallback > 0.05 { seg(fallback, Palette.accent, scale) }
- seg(max(0.02, s.translate - s.queue - fallback), Palette.ink, scale)
- // Speak-back counts to the first sound, not the whole clip: that's what the other side waits for.
- if let v = s.firstAudio ?? s.voice { seg(v, Color(red: 0.60, green: 0.63, blue: 0.67), scale) }
- }
- .frame(width: 200, alignment: .leading).clipped()
- }
-
- private func seg(_ seconds: Double, _ color: Color, _ scale: CGFloat) -> some View {
- RoundedRectangle(cornerRadius: 2).fill(color).frame(width: max(2, CGFloat(seconds) * scale), height: 10)
- }
-
- private static let clock: DateFormatter = {
- let f = DateFormatter()
- f.dateFormat = "HH:mm:ss"
- return f
- }()
-
- private func copy() {
- let text = diagnostics.report(version: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
- service: service)
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(text, forType: .string)
- copied = true
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { copied = false }
- }
-}
-
diff --git a/Sources/LiveSubs/DiagnosticsView.swift b/Sources/LiveSubs/DiagnosticsView.swift
new file mode 100644
index 0000000..fe1f815
--- /dev/null
+++ b/Sources/LiveSubs/DiagnosticsView.swift
@@ -0,0 +1,386 @@
+import AppKit
+import SwiftUI
+
+// MARK: - View (settings › 诊断)
+
+struct DiagnosticsView: View {
+ @ObservedObject var diagnostics: Diagnostics
+ /// The service in settings: names the group, and the empty page before any request.
+ var service: AIConfig
+ @State private var copied = false
+ @State private var tick = Date()
+ private let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ Text(subtitle).font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.top, -8)
+ if empty {
+ // Nothing measured yet: four dashes, a grey bar and zeros read as broken. Show
+ // what each stage is and the shape a sentence will take instead.
+ pipeline
+ emptyChannels
+ emptyRecent
+ } else {
+ // What people feel; each step's time is in the list below.
+ HStack(spacing: 8) {
+ tile(L("对方说完 → 你看到字幕"), diagnostics.endToEnd, dark: true)
+ tile(L("你说完 → 对方听到"), diagnostics.toRoom)
+ }
+ uses
+ totals
+ recent
+ }
+ HStack(spacing: 8) {
+ SoftButton(copied ? L("已复制") : L("复制诊断信息"), dark: !empty) { copy() }
+ .disabled(empty)
+ // The meeting folder holds metrics.jsonl; the log only exists in dev builds or with `debug` on.
+ SoftButton(diagnostics.folder() == nil ? L("打开日志") : L("打开本场数据")) {
+ NSWorkspace.shared.open(diagnostics.folder() ?? URL(fileURLWithPath: DevBuild.logPath))
+ }
+ Spacer()
+ Text("只记时间和次数,不存字幕原文").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ .onReceive(timer) { tick = $0 }
+ }
+
+ private var empty: Bool { diagnostics.sentences.isEmpty && diagnostics.calls.isEmpty }
+
+ private var subtitle: String {
+ guard let s = diagnostics.startedAt else { return L("开始聆听后,这里会显示每句话的耗时明细") }
+ if empty { return L("有人说话后,这里会显示每句话的耗时明细") }
+ let m = Int((diagnostics.endedAt ?? tick).timeIntervalSince(s) / 60)
+ return L("这场会议 · \(m) 分钟 · \(diagnostics.heard.count) 句 · 同声传译 \(diagnostics.said.count) 次")
+ }
+
+ private func tile(_ title: String, _ s: Diagnostics.Stat?, dark: Bool = false) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title).font(.system(size: 11)).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.secondary)
+ Text(s.map { String(format: "%.1fs", $0.p50) } ?? "—").font(.system(size: 20, weight: .bold).monospacedDigit())
+ .foregroundStyle(dark ? Color.white : Palette.ink)
+ Text(s.map { String(format: "p95 %.1fs · %d", $0.p95, $0.n) } ?? L("暂无数据"))
+ .font(.system(size: 11).monospacedDigit()).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.tertiary)
+ }
+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 12).fill(dark ? Palette.ink : Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(dark ? .clear : Palette.line, lineWidth: 1))
+ }
+
+ // MARK: Before any sentence
+
+ private var pipeline: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ Text("一句话的路").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Spacer()
+ Text("还没有句子").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ TimelineView(.animation(minimumInterval: 1 / 30)) { ctx in
+ GeometryReader { g in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.fill).frame(height: 4)
+ Circle().fill(Palette.accent).frame(width: 10, height: 10)
+ .offset(x: phase(ctx.date, period: 2.4) * (g.size.width - 10))
+ }
+ .frame(maxHeight: .infinity)
+ }
+ }
+ .frame(height: 10).padding(.horizontal, 14).accessibilityHidden(true)
+ HStack(alignment: .top, spacing: 8) {
+ stage(L("识别定稿"), L("听清这句话"))
+ stage(L("翻译"), L("译成目标语言"))
+ stage(L("说完到上屏"), L("你感到的延迟"))
+ stage(L("纪要一轮"), L("更新一次纪要"))
+ }
+ }
+ .padding(16)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func stage(_ title: String, _ detail: String) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ Text("– s").font(.system(size: 18, weight: .bold).monospacedDigit()).foregroundStyle(Palette.placeholder)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 4)
+ }
+
+ private var emptyChannels: some View {
+ SettingsCard {
+ SettingsRow(title: L("AI 服务"), detail: service.provider.id == .ling ? L("账号上限约每秒 2 次") : nil) {
+ Text("\(service.provider.name) · \(Self.short(service.textModel))").font(.system(size: 12))
+ .foregroundStyle(Palette.secondary).lineLimit(1)
+ }
+ SettingsRow(title: L("本场用量"), divider: false) {
+ Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ }
+
+ private var emptyRecent: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("最近的句子").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ HStack(spacing: 10) {
+ Text("示例 · 对方").font(.system(size: 12)).foregroundStyle(Palette.tertiary).frame(width: 150, alignment: .leading)
+ HStack(spacing: 1) {
+ RoundedRectangle(cornerRadius: 2).fill(Color(red: 0.42, green: 0.44, blue: 0.50)).frame(width: 70)
+ RoundedRectangle(cornerRadius: 2).fill(Color(red: 0.96, green: 0.78, blue: 0.71)).frame(width: 18)
+ RoundedRectangle(cornerRadius: 2).fill(Palette.ink).frame(width: 46)
+ }
+ .frame(height: 10)
+ Spacer(minLength: 0)
+ Text("2.4s").font(.system(size: 12, weight: .semibold).monospacedDigit())
+ }
+ .opacity(0.5)
+ HStack(spacing: 14) {
+ legend(Color(red: 0.42, green: 0.44, blue: 0.50), L("识别"))
+ legend(Color(red: 0.96, green: 0.78, blue: 0.71), L("排队"))
+ legend(Palette.ink, L("翻译"))
+ }
+ }
+ .padding(14)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func legend(_ color: Color, _ title: String) -> some View {
+ HStack(spacing: 5) {
+ RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 8, height: 8)
+ Text(title).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ }
+
+ /// The service's own ids (ling, zenmux…), as recorded in `via` and the fallbacks.
+ private static func serviceName(_ id: String) -> String? { AIProvider.all.first { $0.id.rawValue == id }?.name }
+
+ private static func color(_ via: String) -> Color {
+ switch via {
+ case "google": Palette.accent
+ case "ming": Palette.accentInk
+ default: serviceName(via) != nil ? Palette.ink : Color(red: 0.72, green: 0.74, blue: 0.78)
+ }
+ }
+
+ private static func name(_ via: String) -> String {
+ switch via {
+ case "google": "Google"
+ case "apple": L("本机")
+ case "ming": L("Ming 语音")
+ default: serviceName(via) ?? L("没译出")
+ }
+ }
+
+ private static func reason(_ key: String) -> String {
+ let parts = key.split(separator: ":").map(String.init)
+ let who = parts.count < 2 ? "" : parts.first.map { $0 == "google" ? "Google" : $0 == "notes" ? L("纪要") : $0 == "ming" ? L("Ming 语音") : serviceName($0) ?? L("本机") } ?? ""
+ let why: String
+ switch parts.last ?? "" {
+ case "hijacked": why = L("被搜索劫持")
+ case "rateLimited", "429": why = L("限流")
+ case "timeout": why = L("超时")
+ case "unparsed": why = L("回复格式不对")
+ case "network": why = L("网络错误")
+ case "unavailable": why = L("未安装语言包")
+ default: why = parts.last ?? ""
+ }
+ return who.isEmpty ? why : "\(who) \(why)"
+ }
+
+ /// "inclusionai/ling-3.0-flash" → "ling-3.0-flash": the vendor is in the group name already.
+ static func short(_ model: String) -> String { model.split(separator: "/").last.map(String.init) ?? model }
+
+ private static func seconds(_ x: Double) -> String { String(format: "%.1fs", x) }
+
+ private static func count(_ n: Int) -> String { n >= 1000 ? String(format: "%.1fk", Double(n) / 1000) : "\(n)" }
+
+ private static func title(_ role: String) -> String {
+ switch role {
+ case "translate": L("整句翻译")
+ case "heard-me": L("听懂你说的")
+ case "voice": L("同传声音")
+ case "notes": L("实时纪要")
+ case "speakers": L("认出说话人")
+ default: role
+ }
+ }
+
+ /// 1A: one row per use, a single big number (p50) with p95 under it. Uses that follow the AI
+ /// service come first; the ones fixed on this Mac or Google come after, so switching service
+ /// visibly changes only the first group.
+ private var uses: some View {
+ let uses = diagnostics.uses
+ let retreats = diagnostics.retreats
+ let current = service.provider.id.rawValue
+ return VStack(alignment: .leading, spacing: 0) {
+ group(L("跟着 AI 服务走 · \(service.provider.name)"))
+ if uses.isEmpty {
+ Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary).padding(.vertical, 9)
+ }
+ ForEach(Array(uses.enumerated()), id: \.element.id) { i, u in
+ let model = (u.provider == current ? "" : (Self.serviceName(u.provider) ?? u.provider) + " · ") + Self.short(u.model)
+ var foot = [L("\(u.n) 次")]
+ if u.tokens > 0 { foot.append("\(Self.count(u.tokens)) token") }
+ if u.chars > 0 { foot.append(L("\(u.chars) 字")) }
+ var pill: String?
+ let why = u.reasons.prefix(2).map { "\(Self.reason($0.0)) \($0.1)" }.joined(separator: "、")
+ if u.role == "translate", let top = retreats.first {
+ let n = retreats.reduce(0) { $0 + $1.1 }
+ pill = L("\(n) 句退回 \(Self.name(top.0))") + (why.isEmpty ? "" : " · " + why)
+ } else if u.failed > 0 {
+ pill = L("失败 \(u.failed)") + (why.isEmpty ? "" : " · " + why)
+ } else {
+ foot.append(L("没有失败"))
+ }
+ return useRow(Self.title(u.role), u.role == "voice" ? model + " · " + L("到开始出声") : model,
+ u.latency, foot: foot, pill: pill, divider: i > 0)
+ }
+ let fixed = fixedRows
+ if !fixed.isEmpty {
+ group(L("不受换服务影响")).padding(.top, 12)
+ ForEach(Array(fixed.enumerated()), id: \.offset) { i, r in
+ useRow(r.title, r.detail, r.stat, foot: r.foot, dim: true, divider: i > 0)
+ }
+ }
+ }
+ .padding(14)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private var fixedRows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] {
+ var rows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] = []
+ if let r = diagnostics.recognize { rows.append((L("识别对方"), L("本机识别"), r, [L("\(r.n) 句")])) }
+ if let r = diagnostics.recognizeMine { rows.append((L("识别你说的"), L("本机识别"), r, [L("\(r.n) 句")])) }
+ let d = diagnostics.drafts
+ if d.n > 0 {
+ rows.append((L("半句翻译"), "Google", diagnostics.draftStat,
+ [L("\(d.n) 次"), d.failed > 0 ? L("失败 \(d.failed)") : L("没有失败")]))
+ }
+ return rows
+ }
+
+ private func group(_ title: String) -> some View {
+ Text(title).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.tertiary).padding(.bottom, 2)
+ }
+
+ private func useRow(_ title: String, _ detail: String, _ s: Diagnostics.Stat?, foot: [String] = [], pill: String? = nil,
+ dim: Bool = false, divider: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.system(size: 13, weight: dim ? .medium : .semibold)).foregroundStyle(Palette.ink)
+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)
+ }
+ Spacer(minLength: 0)
+ VStack(alignment: .trailing, spacing: 1) {
+ Text(s.map { Self.seconds($0.p50) } ?? "—")
+ .font(.system(size: dim ? 15 : 18, weight: .bold).monospacedDigit()).foregroundStyle(Palette.ink)
+ if let s { Text("p95 " + Self.seconds(s.p95)).font(.system(size: 10).monospacedDigit()).foregroundStyle(Palette.tertiary) }
+ }
+ }
+ if pill != nil || !foot.isEmpty {
+ HStack(spacing: 6) {
+ if let pill {
+ Text(pill).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Palette.accentInk).lineLimit(1)
+ .padding(.horizontal, 7).padding(.vertical, 1.5)
+ .background(Capsule().fill(Palette.accentPale))
+ }
+ Text(foot.joined(separator: " · ")).font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.tertiary)
+ .lineLimit(1)
+ }
+ }
+ }
+ .padding(.vertical, 9)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .overlay(alignment: .top) { if divider { Rectangle().fill(Palette.line).frame(height: 1) } }
+ }
+
+ private var totals: some View {
+ let _ = tick
+ let t = diagnostics.tokens
+ let n = diagnostics.calls.count
+ let chars = diagnostics.voiceChars
+ return SettingsCard {
+ if service.provider.id == .ling {
+ SettingsRow(title: L("Ling 请求速度"), detail: L("账号上限约每秒 2 次")) {
+ Text(String(format: L("%.1f / 2 次每秒"), diagnostics.lingRate)).font(.system(size: 12).monospacedDigit())
+ .foregroundStyle(Palette.secondary)
+ }
+ }
+ SettingsRow(title: L("排队最久"), detail: L("请求太密时,纪要让翻译先走")) {
+ Text(String(format: "%.1fs", diagnostics.maxQueue)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)
+ }
+ SettingsRow(title: L("本场用量"), detail: L("服务返回的数,以服务的账单为准"), divider: false) {
+ Text(chars > 0 ? L("\(n) 次 · \(t.0 + t.1) token · \(chars) 字语音") : L("\(n) 次 · \(t.0 + t.1) token"))
+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+
+ /// The last few sentences as stacked bars: recognise · queue · translate (· voice).
+ private var recent: some View {
+ let rows = Array(diagnostics.sentences.suffix(6).reversed())
+ return VStack(alignment: .leading, spacing: 0) {
+ Text("最近的句子").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).padding(.bottom, 8)
+ if rows.isEmpty {
+ Text("还没有").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ ForEach(rows) { s in
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text("\(Self.clock.string(from: s.at)) \(s.side == "me" ? L("你") : L("对方"))").font(.system(size: 12).monospacedDigit())
+ Text(s.fallbacks.isEmpty ? L("\(Self.name(s.via)) · \(s.chars) 字") : s.fallbacks.map(Self.reason).joined(separator: "、") + " → " + Self.name(s.via))
+ .font(.system(size: 10)).foregroundStyle(s.fallbacks.isEmpty ? Palette.tertiary : Palette.accentInk).lineLimit(1)
+ }
+ .frame(width: 150, alignment: .leading)
+ bar(s)
+ Spacer(minLength: 0)
+ Text(String(format: "%.1fs", s.total + (s.firstAudio ?? s.voice ?? 0))).font(.system(size: 12, weight: .semibold).monospacedDigit())
+ }
+ .frame(height: 34)
+ }
+ }
+ .padding(14)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func bar(_ s: SentenceTiming) -> some View {
+ let scale: CGFloat = 50 // points per second; 4 s ≈ 200 pt
+ let fallback = s.failed
+ return HStack(spacing: 1) {
+ if let r = s.recognize { seg(r, Color(red: 0.42, green: 0.44, blue: 0.50), scale) }
+ if s.queue > 0.05 { seg(s.queue, Color(red: 0.96, green: 0.78, blue: 0.71), scale) }
+ if fallback > 0.05 { seg(fallback, Palette.accent, scale) }
+ seg(max(0.02, s.translate - s.queue - fallback), Palette.ink, scale)
+ // Speak-back counts to the first sound, not the whole clip: that's what the other side waits for.
+ if let v = s.firstAudio ?? s.voice { seg(v, Color(red: 0.60, green: 0.63, blue: 0.67), scale) }
+ }
+ .frame(width: 200, alignment: .leading).clipped()
+ }
+
+ private func seg(_ seconds: Double, _ color: Color, _ scale: CGFloat) -> some View {
+ RoundedRectangle(cornerRadius: 2).fill(color).frame(width: max(2, CGFloat(seconds) * scale), height: 10)
+ }
+
+ private static let clock: DateFormatter = {
+ let f = DateFormatter()
+ f.dateFormat = "HH:mm:ss"
+ return f
+ }()
+
+ private func copy() {
+ let text = diagnostics.report(version: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
+ service: service)
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ copied = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { copied = false }
+ }
+}
diff --git a/Sources/LiveSubs/Languages.swift b/Sources/LiveSubs/Languages.swift
index 3729f74..eda95da 100644
--- a/Sources/LiveSubs/Languages.swift
+++ b/Sources/LiveSubs/Languages.swift
@@ -1,9 +1,5 @@
-import AppKit
-import AVFoundation
-import AudioToolbox
-import CoreAudio
-import CoreMedia
-import Speech
+// Pure Foundation: the iOS app shares this file (ios/shared-sources.txt).
+import Foundation
// MARK: - Languages
diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swift
index 6b19fea..2bf68ef 100644
--- a/Sources/LiveSubs/Ling.swift
+++ b/Sources/LiveSubs/Ling.swift
@@ -67,7 +67,13 @@ enum AIKey {
}
}
try fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)
+ #if os(iOS)
+ // Readable after the first unlock: listening goes on on the lock screen, and a meeting
+ // started from the Action Button while locked still needs the key for the notes.
+ try Data(key.utf8).write(to: file, options: .completeFileProtectionUntilFirstUserAuthentication)
+ #else
try Data(key.utf8).write(to: file)
+ #endif
var url = file
var values = URLResourceValues()
values.isExcludedFromBackup = true
diff --git a/Sources/LiveSubs/Localization.swift b/Sources/LiveSubs/Localization.swift
index 0fbec88..64ce29c 100644
--- a/Sources/LiveSubs/Localization.swift
+++ b/Sources/LiveSubs/Localization.swift
@@ -18,3 +18,5 @@ func dateText(_ date: Date, _ template: String) -> String {
f.setLocalizedDateFormatFromTemplate(template)
return f.string(from: date)
}
+
+let appDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? L("知了")
diff --git a/Sources/LiveSubs/Recognition.swift b/Sources/LiveSubs/Recognition.swift
index 03b979a..a45dec6 100644
--- a/Sources/LiveSubs/Recognition.swift
+++ b/Sources/LiveSubs/Recognition.swift
@@ -11,12 +11,28 @@ enum Recognition {
/// Not kept in settings: two dev copies share them.
nonisolated(unsafe) static var forceLegacy = DevBuild.isDev && ProcessInfo.processInfo.environment["CICADA_RECOGNIZER"] == "legacy"
+ /// Set by the iOS simulator's dev build only: its speech models are empty placeholders, so it
+ /// hands the audio to the Mac it runs on (ios/tools/host-recognizer), which recognizes it on
+ /// device with this same file. Nil on a Mac and on an iPhone.
+ nonisolated(unsafe) static var host: ((_ locale: String, _ drafts: Bool) throws -> RecognitionStream)?
+
static var legacy: Bool {
+ if host != nil { return false }
if #available(macOS 26, *) { return forceLegacy }
return true
}
- static var name: String { legacy ? "legacy" : "analyzer" }
+ static var name: String { host != nil ? "mac-host" : legacy ? "legacy" : dictationModel ? "dictation" : "analyzer" }
+
+ /// iOS only: a device without `SpeechTranscriber` (older iPhones, the simulator) still has the
+ /// on-device dictation model, `DictationTranscriber`, which runs in the same `SpeechAnalyzer`.
+ /// The Mac keeps `SpeechTranscriber` or the older recognizer, as before.
+ static var dictationModel: Bool {
+ #if CICADA_IOS
+ if #available(macOS 26, *) { return !SpeechTranscriber.isAvailable }
+ #endif
+ return false
+ }
/// Apple's on-device translation can be made outside a SwiftUI view only on 26 (`Translator.viaApple`).
static var hasOnDeviceTranslation: Bool {
@@ -38,7 +54,8 @@ enum Recognition {
enum ModelStatus { case installed, downloadable, unsupported }
static var isAvailable: Bool {
- if !legacy, #available(macOS 26, *) { return SpeechTranscriber.isAvailable }
+ if host != nil { return true }
+ if !legacy, #available(macOS 26, *) { return SpeechTranscriber.isAvailable || dictationModel }
return true
}
@@ -90,14 +107,16 @@ enum Recognition {
/// BCP-47 ids of the languages that can be recognized right now without a download.
static func installedLocales() async -> Set<String> {
if !legacy, #available(macOS 26, *) {
- return Set(await SpeechTranscriber.installedLocales.map { $0.identifier(.bcp47) })
+ let installed = dictationModel ? await DictationTranscriber.installedLocales : await SpeechTranscriber.installedLocales
+ return Set(installed.map { $0.identifier(.bcp47) })
}
return Set(sourceLanguages.map(\.locale).filter { LegacyStream.onDevice($0) })
}
static func status(_ locale: String) async -> ModelStatus {
+ if host != nil { return .installed }
if !legacy, #available(macOS 26, *) {
- switch await AssetInventory.status(forModules: [Analyzer.transcriber(locale)]) {
+ switch await AssetInventory.status(forModules: [Analyzer.module(locale)]) {
case .installed: return .installed
case .unsupported: return .unsupported
default: return .downloadable
@@ -111,8 +130,9 @@ enum Recognition {
/// Fetches the model for `locale` when it isn't on the Mac; `progress` is called once a
/// download starts. Throws when this Mac can't recognize the language.
static func install(_ locale: String, progress: (Progress) -> Void = { _ in }) async throws {
+ if host != nil { return }
if !legacy, #available(macOS 26, *) {
- let t = Analyzer.transcriber(locale)
+ let t = Analyzer.module(locale)
if await AssetInventory.status(forModules: [t]) == .unsupported { throw unsupported(locale) }
if let request = try await AssetInventory.assetInstallationRequest(supporting: [t]) {
progress(request.progress)
@@ -155,6 +175,7 @@ enum Recognition {
/// `background`: a file being imported; on macOS 14/15 it gives way to a live meeting.
static func start(_ locale: String, drafts: Bool, confidence: Bool = false, speaking: Bool = false,
background: Bool = false) async throws -> RecognitionStream {
+ if let host { return try host(locale, drafts) }
if !legacy, #available(macOS 26, *) {
return try await Analyzer.start(locale, drafts: drafts, confidence: confidence)
}
@@ -166,7 +187,7 @@ enum Recognition {
/// The audio format `start(locale, drafts:)` will want, known before starting one.
static func format(_ locale: String, drafts: Bool) async -> AVAudioFormat {
if !legacy, #available(macOS 26, *) {
- return await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [Analyzer.transcriber(locale, drafts: drafts)])
+ return await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [Analyzer.module(locale, drafts: drafts)])
?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!
}
return LegacyStream.audioFormat
@@ -241,8 +262,18 @@ final class Analyzer: RecognitionStream, @unchecked Sendable {
attributeOptions: confidence ? [.transcriptionConfidence] : [])
}
+ /// What recognizes `locale`: `SpeechTranscriber`, or the dictation model where that is missing (`Recognition.dictationModel`).
+ static func module(_ locale: String, drafts: Bool = false, confidence: Bool = false) -> any SpeechModule {
+ guard Recognition.dictationModel else { return transcriber(locale, drafts: drafts, confidence: confidence) }
+ // .farField: the room is heard from across the table. .frequentFinalization: sentences
+ // come back finished about as often as SpeechTranscriber's.
+ return DictationTranscriber(locale: Locale(identifier: locale), contentHints: [.farField], transcriptionOptions: [.punctuation],
+ reportingOptions: drafts ? [.volatileResults, .frequentFinalization] : [],
+ attributeOptions: confidence ? [.audioTimeRange, .transcriptionConfidence] : [.audioTimeRange])
+ }
+
static func start(_ locale: String, drafts: Bool, confidence: Bool) async throws -> Analyzer {
- let t = transcriber(locale, drafts: drafts, confidence: confidence)
+ let t = module(locale, drafts: drafts, confidence: confidence)
let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t])
?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!
let analyzer = SpeechAnalyzer(modules: [t])
@@ -253,26 +284,31 @@ final class Analyzer: RecognitionStream, @unchecked Sendable {
return me
}
- private init(_ t: SpeechTranscriber, analyzer: SpeechAnalyzer, format: AVAudioFormat,
+ private init(_ t: any SpeechModule, analyzer: SpeechAnalyzer, format: AVAudioFormat,
input: AsyncStream<AnalyzerInput>.Continuation) {
self.analyzer = analyzer
self.format = format
self.input = input
let (results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)
self.results = results
+ func piece(_ text: AttributedString, _ isFinal: Bool, _ range: CMTimeRange) -> Recognition.Piece {
+ var weighted = 0.0, chars = 0
+ for run in text.runs {
+ guard let c = run.transcriptionConfidence else { continue }
+ let len = text[run.range].characters.count
+ weighted += c * Double(len)
+ chars += len
+ }
+ return .init(text: String(text.characters), isFinal: isFinal,
+ start: CMTimeGetSeconds(range.start), end: CMTimeGetSeconds(range.end),
+ confidence: chars > 0 ? weighted / Double(chars) : nil)
+ }
reader = Task {
do {
- for try await r in t.results {
- var weighted = 0.0, chars = 0
- for run in r.text.runs {
- guard let c = run.transcriptionConfidence else { continue }
- let len = r.text[run.range].characters.count
- weighted += c * Double(len)
- chars += len
- }
- out.yield(.init(text: String(r.text.characters), isFinal: r.isFinal,
- start: CMTimeGetSeconds(r.range.start), end: CMTimeGetSeconds(r.range.end),
- confidence: chars > 0 ? weighted / Double(chars) : nil))
+ if let t = t as? SpeechTranscriber {
+ for try await r in t.results { out.yield(piece(r.text, r.isFinal, r.range)) }
+ } else if let d = t as? DictationTranscriber {
+ for try await r in d.results { out.yield(piece(r.text, r.isFinal, r.range)) }
}
out.finish()
} catch {
diff --git a/Sources/LiveSubs/RecordList.swift b/Sources/LiveSubs/RecordList.swift
new file mode 100644
index 0000000..c06e885
--- /dev/null
+++ b/Sources/LiveSubs/RecordList.swift
@@ -0,0 +1,67 @@
+import Foundation
+
+/// How meetings are listed in the records window (Mac) and the records tab (iOS).
+enum RecordList {
+ /// 今天 / 昨天 / 本周 / then one group per month, newest first.
+ static func groups(_ sessions: [Session]) -> [(title: String, sessions: [Session])] {
+ let cal = Calendar.current
+ var out: [(title: String, sessions: [Session])] = []
+ for s in sessions {
+ let d = s.startedAt
+ let title: String
+ if cal.isDateInToday(d) { title = L("今天") }
+ else if cal.isDateInYesterday(d) { title = L("昨天") }
+ else if cal.isDate(d, equalTo: Date(), toGranularity: .weekOfYear) { title = L("本周") }
+ else if cal.isDate(d, equalTo: Date(), toGranularity: .year) { title = dateText(d, "MMMM") }
+ else { title = dateText(d, "yMMMM") }
+ if out.last?.title == title { out[out.count - 1].sessions.append(s) } else { out.append((title, [s])) }
+ }
+ return out
+ }
+ static func when(_ s: Session) -> String {
+ let cal = Calendar.current
+ return dateText(s.startedAt, cal.isDateInToday(s.startedAt) || cal.isDateInYesterday(s.startedAt) ? "HHmm"
+ : cal.isDate(s.startedAt, equalTo: Date(), toGranularity: .weekOfYear) ? "EEE" : "MMMd")
+ }
+ /// Notes titles often start with the day ("11月2日 产品周会"); under a 今天 heading that only
+ /// pushes the real title out of the row.
+ static func listTitle(_ s: Session) -> String {
+ let title = s.displayTitle
+ for prefix in [dateText(s.startedAt, "MMMd"), dateText(s.startedAt, "MMMMd")] where title.hasPrefix(prefix) {
+ let rest = title.dropFirst(prefix.count).trimmingCharacters(in: .whitespaces)
+ if !rest.isEmpty { return rest }
+ }
+ return title
+ }
+ /// Still on the stored "会议 <date>" title: not renamed, and no notes title to show.
+ static func untitled(_ s: Session) -> Bool {
+ !(s.renamed ?? !s.title.hasPrefix("会议 ")) && (s.notes?.title ?? "").isEmpty && s.sourceFile == nil
+ }
+
+ static func length(_ s: Session) -> String {
+ let mins = Int(s.duration / 60)
+ if mins < 1 { return L("不到 1 分钟") }
+ return mins < 60 ? L("\(mins) 分钟") : mins % 60 == 0 ? L("\(mins / 60) 小时") : L("\(mins / 60) 小时 \(mins % 60) 分")
+ }
+
+ /// "英 → 中" (short) or "英语 → 中文", from the most common pair among the lines.
+ static func pair(_ s: Session, short: Bool) -> String? {
+ let pairs = Dictionary(grouping: s.lines.filter { $0.speaker != "me" }, by: { "\(lang($0.srcLang))|\(lang($0.dstLang))" })
+ guard let top = pairs.max(by: { $0.value.count < $1.value.count })?.key else { return nil }
+ let p = top.split(separator: "|").map(String.init)
+ guard p.count == 2, p[0] != p[1] else { return nil }
+ func name(_ c: String) -> String {
+ let names = ["en": L("英语"), "ja": L("日语"), "zh-CN": L("中文"), "zh-TW": L("繁中"), "ko": L("韩语"),
+ "es": L("西语"), "fr": L("法语"), "de": L("德语"), "pt": L("葡语")]
+ guard let n = names[c] else { return c.uppercased() }
+ guard short else { return n }
+ return uiIsChinese ? String(n.prefix(1)) : c == "zh-TW" ? "ZH-TW" : String(c.prefix(2)).uppercased()
+ }
+ return "\(name(p[0])) → \(name(p[1]))"
+ }
+
+ private static func lang(_ code: String) -> String {
+ let base = String(code.split(whereSeparator: { $0 == "-" || $0 == "_" }).first ?? "")
+ return base == "zh" ? (code.contains("Hant") || code.hasSuffix("TW") || code.hasSuffix("HK") ? "zh-TW" : "zh-CN") : base
+ }
+}
diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swift
index 1c3458d..044967a 100644
--- a/Sources/LiveSubs/SessionStore.swift
+++ b/Sources/LiveSubs/SessionStore.swift
@@ -1,4 +1,6 @@
+#if os(macOS)
import AppKit
+#endif
import Foundation
struct TranscriptLine: Codable, Identifiable, Equatable {
@@ -460,6 +462,8 @@ enum TranscriptExport {
return out
}
+ #if os(macOS)
+ // `.officeOpenXML` is macOS-only; iOS needs its own writer (docs/ios-plan.md).
static func docx(_ s: Session) throws -> Data {
let doc = NSMutableAttributedString()
func add(_ text: String, size: CGFloat, weight: NSFont.Weight = .regular, color: NSColor = .black, after: CGFloat = 4) {
@@ -505,4 +509,5 @@ enum TranscriptExport {
return try doc.data(from: NSRange(location: 0, length: doc.length),
documentAttributes: [.documentType: NSAttributedString.DocumentType.officeOpenXML])
}
+ #endif
}
diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swift
index be49f0a..6652378 100644
--- a/Sources/LiveSubs/SettingsWindow.swift
+++ b/Sources/LiveSubs/SettingsWindow.swift
@@ -279,8 +279,6 @@ struct HealthMark: View {
}
}
-let appDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? L("知了")
-
// MARK: - Virtual microphone checklist
/// The one place the virtual mic is set up: onboarding step 4 and the settings window.
diff --git a/Sources/LiveSubs/SpeakerID.swift b/Sources/LiveSubs/SpeakerID.swift
index d886ba2..140f093 100644
--- a/Sources/LiveSubs/SpeakerID.swift
+++ b/Sources/LiveSubs/SpeakerID.swift
@@ -1,8 +1,8 @@
import Accelerate
import AVFoundation
import CoreML
+import Combine
import Foundation
-import SwiftUI
// 说话人识别: telling the other side's voices apart (设置 › 通用). Each heard line's
// audio becomes a voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0, bundled as Core ML),
@@ -460,333 +460,3 @@ final class SpeakerNamer: ObservableObject {
}
}
}
-
-// MARK: - Views
-
-/// Colours for 说话人 1, 2, 3…, cycling after four: not the accent ("live", and 你) nor link blue
-/// (times in the records window), distinct in lightness, all ≥ 4.5:1 on white.
-enum SpeakerColor {
- private static let inks: [Color] = [Color(red: 0.059, green: 0.482, blue: 0.424), Color(red: 0.478, green: 0.298, blue: 0.761),
- Color(red: 0.690, green: 0.227, blue: 0.478), Color(red: 0.541, green: 0.353, blue: 0)]
- static func ink(_ n: Int) -> Color { inks[(max(1, n) - 1) % inks.count] }
-}
-
-/// "说话人 2" above a line.
-/// The names given to voices in the meeting on show, by speaker number (set on the transcript's container).
-private struct SpeakerNamesKey: EnvironmentKey { static let defaultValue: [Int: String] = [:] }
-extension EnvironmentValues {
- var speakerNames: [Int: String] {
- get { self[SpeakerNamesKey.self] }
- set { self[SpeakerNamesKey.self] = newValue }
- }
-}
-
-struct SpeakerTag: View {
- let number: Int
- @Environment(\.speakerNames) private var names
- var body: some View {
- HStack(spacing: 5) {
- Circle().fill(SpeakerColor.ink(number)).frame(width: 6, height: 6)
- Text(SpeakerLabels.label(number, names)).font(.system(size: 11, weight: .semibold)).foregroundStyle(SpeakerColor.ink(number))
- }
- }
-}
-
-/// A line from the other side whose voice isn't one of the people on show.
-struct UnknownSpeakerTag: View {
- var body: some View {
- HStack(spacing: 5) {
- Circle().strokeBorder(Palette.tertiary, lineWidth: 1).frame(width: 6, height: 6)
- Text("未识别").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.tertiary)
- }
- .help(L("没认出是谁:太短,或和已知的声音都不像"))
- }
-}
-
-/// Above the transcript once voices are told apart: who is speaking, and a one-click way out. Each
-/// person opens `SpeakerEditor`: a popover in the records window; in the notes window (`editing`
-/// set) a card right below the row, since a popover in a panel that never activates the app closes
-/// as soon as it opens.
-struct SpeakerStrip: View {
- @ObservedObject var model: AppModel
- let session: Session
- /// The notes window's voice being edited: the editor opens inline instead of as a popover.
- var editing: Binding<Int?>? = nil
- @State private var popover: Int?
-
- var body: some View {
- let numbers = SpeakerLabels.voiceNumbers(session.lines)
- let names = SpeakerLabels.names(session)
- VStack(alignment: .leading, spacing: 10) {
- HStack(alignment: .top, spacing: 8) {
- FlowLayout(spacing: 6) {
- ForEach(numbers.sorted { $0.value < $1.value }, id: \.key) { voice, n in
- let on = (editing?.wrappedValue ?? popover) == voice
- Button {
- if let editing { editing.wrappedValue = on ? nil : voice } else { popover = voice }
- } label: {
- HStack(spacing: 5) {
- Circle().fill(on ? Color.white : SpeakerColor.ink(n)).frame(width: 6, height: 6)
- Text(SpeakerLabels.label(n, names)).font(.system(size: 11, weight: .semibold))
- .foregroundStyle(on ? Color.white : SpeakerColor.ink(n))
- }
- .fixedSize()
- .padding(.horizontal, 8).frame(height: 22)
- .background(Capsule().fill(on ? SpeakerColor.ink(n) : SpeakerColor.ink(n).opacity(0.08)))
- .contentShape(Capsule())
- }
- .buttonStyle(.plain)
- .help(SpeakerLabels.guessed(session)[n].map { _ in L("Ling 从对话里认出,点一下可以改") } ?? L("改名字,或和别人合并"))
- .popover(isPresented: Binding(get: { editing == nil && popover == voice }, set: { if !$0 { popover = nil } }), arrowEdge: .bottom) {
- SpeakerEditor(model: model, namer: model.speakerNamer, sessionID: session.id, voice: voice) { popover = nil }
- }
- }
- }
- Spacer(minLength: 0)
- Button { model.settings.speakerVoices = false } label: {
- Text("不准?关掉").font(.system(size: 11)).foregroundStyle(Palette.secondary).underline().fixedSize()
- }
- .buttonStyle(.plain)
- .frame(height: 22)
- .help(L("关掉说话人识别,记录里的名字一起收起"))
- }
- if let editing, let voice = editing.wrappedValue, numbers[voice] != nil {
- SpeakerEditor(model: model, namer: model.speakerNamer, sessionID: session.id, voice: voice, inline: true) {
- editing.wrappedValue = nil
- model.notesWindow.returnKeyboard()
- }
- .id(voice)
- }
- }
- .onAppear { model.speakerNamer.guess(session.id) }
- }
-}
-
-/// Correct one voice: its name (Ling's guess and people from 人名和术语 are a click away), or merge it
-/// into another voice. `inline` (the notes window): a click on a name or a merge applies at once.
-struct SpeakerEditor: View {
- @ObservedObject var model: AppModel
- @ObservedObject var namer: SpeakerNamer
- let sessionID: String
- let voice: Int
- var inline = false
- let close: () -> Void
- @State private var draft = ""
- @State private var allMerges = false
- @FocusState private var typing: Bool
-
- private var session: Session? { model.store.session(sessionID) }
-
- 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)
- let names = SpeakerLabels.names(s)
- let guess = SpeakerLabels.guessed(s)[n]
- VStack(alignment: .leading, spacing: 12) {
- HStack(spacing: 6) {
- Circle().fill(SpeakerColor.ink(n)).frame(width: 8, height: 8)
- Text(SpeakerLabels.label(n, names)).font(.system(size: 14, weight: .bold))
- Text("说了 \(s.lines.filter { $0.voice == voice }.count) 句").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
- Spacer()
- if inline {
- Button(action: close) {
- Image(systemName: "xmark").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
- .frame(width: 24, height: 24).contentShape(Rectangle())
- }
- .buttonStyle(.plain).help("收起").accessibilityLabel(L("收起"))
- }
- }
- VStack(alignment: .leading, spacing: 6) {
- Text("是谁").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
- let picks = suggestions(s, names: names, number: n, guess: guess)
- if !picks.isEmpty {
- FlowLayout(spacing: 6) {
- ForEach(picks, id: \.self) { name in
- choice(name, dark: name == names[n]) {
- if inline { apply(s, guess, name) } else { draft = name }
- }
- }
- }
- }
- HStack(spacing: 8) {
- TextField(L("输入名字"), text: $draft).textFieldStyle(.roundedBorder)
- .focused($typing)
- .onSubmit { apply(s, guess, draft) }
- .onExitCommand { close() }
- if inline, typing || draft != (names[n] ?? "") {
- SoftButton(L("保存"), dark: true) { apply(s, guess, draft) }
- }
- }
- if inline && typing {
- // The panel holds the keyboard only while a name is typed; Return or Esc gives it back.
- Text("键盘暂时在这里,会议软件收不到 · 回车保存 · Esc 交还")
- .font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk)
- .fixedSize(horizontal: false, vertical: true)
- } else if let guess {
- HStack(alignment: .top, spacing: 8) {
- Text(guess.evidence.isEmpty ? L("Ling 从对话里认出") : L("Ling 从对话里认出:\(guess.evidence)"))
- .font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(2)
- Spacer(minLength: 6)
- Button(L("不是 TA")) {
- model.renameSpeaker(session: s.id, voice: voice, "")
- close()
- }
- .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.secondary)
- }
- } else if namer.busy.contains(s.id) {
- Text("Ling 正在从对话里找名字…").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
- }
- }
- let others = numbers.filter { $0.key != voice }.sorted { $0.value < $1.value }
- if !others.isEmpty {
- VStack(alignment: .leading, spacing: 6) {
- Text("其实是同一个人").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
- FlowLayout(spacing: 6) {
- ForEach(allMerges ? others : Array(others.prefix(3)), id: \.key) { other, on in
- choice(L("并入 \(SpeakerLabels.label(on, names))")) {
- model.mergeSpeaker(session: s.id, voice, into: other)
- close()
- }
- }
- if others.count > 3 && !allMerges {
- choice(L("更多")) { allMerges = true }
- }
- }
- }
- }
- if !inline {
- HStack(spacing: 8) {
- Spacer()
- SoftButton(L("取消")) { close() }
- SoftButton(L("完成"), dark: true) { apply(s, guess, draft) }
- }
- }
- }
- .padding(inline ? 14 : 16)
- .frame(width: inline ? nil : 320)
- .frame(maxWidth: inline ? .infinity : nil, alignment: .leading)
- .background {
- if inline {
- RoundedRectangle(cornerRadius: 14).fill(Color.white)
- .shadow(color: .black.opacity(0.08), radius: 10, y: 4)
- .overlay(RoundedRectangle(cornerRadius: 14).stroke(Palette.line, lineWidth: 1))
- }
- }
- .onAppear { draft = names[n] ?? "" }
- }
- }
-
- private func choice(_ title: String, dark: Bool = false, action: @escaping () -> Void) -> some View {
- Button(action: action) {
- Text(title).font(.system(size: 12, weight: .semibold))
- .foregroundStyle(dark ? Color.white : Palette.ink)
- .padding(.horizontal, 10).frame(height: 28)
- .background(RoundedRectangle(cornerRadius: 8).fill(dark ? Palette.ink : Color.white))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(dark ? Palette.ink : Palette.line, lineWidth: 1))
- .fixedSize()
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
-
- /// Ling's guess first, then people the notes mention, without names other voices already have.
- private func suggestions(_ s: Session, names: [Int: String], number: Int, guess: VoiceGuess?) -> [String] {
- let taken = Set(names.filter { $0.key != number }.values)
- var out: [String] = []
- if let g = s.voiceGuesses?[String(voice)]?.name ?? guess?.name { out.append(g) }
- for t in NoteTerm.people(s.notes?.terms ?? []) where !out.contains(t) && !taken.contains(t) { out.append(t) }
- if let mine = names[number], !out.contains(mine) { out.insert(mine, at: 0) }
- return Array(out.prefix(4))
- }
-
- /// Keeping Ling's name stores nothing, so a later, better guess can still replace it.
- private func apply(_ s: Session, _ guess: VoiceGuess?, _ typed: String) {
- let name = typed.trimmingCharacters(in: .whitespacesAndNewlines)
- if let guess, name == guess.name { model.renameSpeaker(session: s.id, voice: voice, nil) }
- else if s.voiceNames?[String(voice)] != nil || !name.isEmpty { model.renameSpeaker(session: s.id, voice: voice, name) }
- close()
- }
-}
-
-/// "这句是谁说的": the people on show, the ones speaking just before and after first. Picked → done.
-struct LineSpeakerPicker: View {
- /// Voice → speaker number, for the voices on show.
- let voices: [Int: Int]
- let current: Int?
- let nearby: [Int]
- let several: Bool
- let pick: (Int) -> Void
- @Environment(\.speakerNames) private var names
-
- var body: some View {
- let order = voices.keys.sorted { a, b in
- let ia = nearby.firstIndex(of: a) ?? Int.max, ib = nearby.firstIndex(of: b) ?? Int.max
- return ia != ib ? ia < ib : voices[a]! < voices[b]!
- }
- VStack(alignment: .leading, spacing: 8) {
- Text(several ? "这段是谁说的" : "这句是谁说的").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
- FlowLayout(spacing: 6) {
- ForEach(order, id: \.self) { v in
- let n = voices[v]!
- Button { pick(v) } label: {
- HStack(spacing: 5) {
- Circle().fill(SpeakerColor.ink(n)).frame(width: 6, height: 6)
- Text(SpeakerLabels.label(n, names)).font(.system(size: 12, weight: .semibold)).foregroundStyle(SpeakerColor.ink(n))
- }
- .padding(.horizontal, 9).frame(height: 28)
- .background(RoundedRectangle(cornerRadius: 8).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(v == current ? SpeakerColor.ink(n) : Palette.line, lineWidth: 1))
- .fixedSize()
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- }
- }
- }
-}
-
-/// "说话人 6 已改成 David · 撤销", for a few seconds after a speaker edit.
-struct SpeakerUndoToast: View {
- @ObservedObject var model: AppModel
- let session: String?
-
- var body: some View {
- if let u = model.speakerUndo, u.session == session, !u.text.isEmpty {
- HStack(spacing: 14) {
- Text(u.text).font(.system(size: 13)).foregroundStyle(.white).lineLimit(2)
- Button("撤销") { model.undoSpeakerEdit() }
- .buttonStyle(.plain).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.accentPale)
- }
- .padding(.horizontal, 14).frame(minHeight: 38)
- .background(RoundedRectangle(cornerRadius: 10).fill(Palette.ink).shadow(color: .black.opacity(0.2), radius: 12, y: 6))
- .padding(.bottom, 18)
- .transition(.opacity)
- }
- }
-}
-
-/// Debug render (`speakersRender`): the people row and the first lines, labelled as the transcript
-/// labels them (a name only where the speaker changes).
-struct SpeakerPreview: View {
- @ObservedObject var model: AppModel
- let session: Session
- var body: some View {
- let numbers = SpeakerLabels.numbers(session.lines)
- let starts = SpeakerLabels.runStarts(session.lines, numbers)
- VStack(alignment: .leading, spacing: 10) {
- if !numbers.isEmpty { SpeakerStrip(model: model, session: session) }
- ForEach(session.lines.prefix(12)) { l in
- VStack(alignment: .leading, spacing: 3) {
- if !starts.contains(l.id) {
- } else if l.speaker == "me" { Text("你").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk) }
- else if let n = numbers[l.id] { SpeakerTag(number: n) }
- else if !numbers.isEmpty { UnknownSpeakerTag() }
- Text(l.src).font(.system(size: 13)).foregroundStyle(Palette.ink)
- }
- }
- }
- .padding(16)
- }
-}
diff --git a/Sources/LiveSubs/SpeakerViews.swift b/Sources/LiveSubs/SpeakerViews.swift
new file mode 100644
index 0000000..b708881
--- /dev/null
+++ b/Sources/LiveSubs/SpeakerViews.swift
@@ -0,0 +1,331 @@
+import SwiftUI
+
+// The 说话人识别 controls in the notes and records windows; the engine is in SpeakerID.swift.
+
+/// Colours for 说话人 1, 2, 3…, cycling after four: not the accent ("live", and 你) nor link blue
+/// (times in the records window), distinct in lightness, all ≥ 4.5:1 on white.
+enum SpeakerColor {
+ private static let inks: [Color] = [Color(red: 0.059, green: 0.482, blue: 0.424), Color(red: 0.478, green: 0.298, blue: 0.761),
+ Color(red: 0.690, green: 0.227, blue: 0.478), Color(red: 0.541, green: 0.353, blue: 0)]
+ static func ink(_ n: Int) -> Color { inks[(max(1, n) - 1) % inks.count] }
+}
+
+/// "说话人 2" above a line.
+/// The names given to voices in the meeting on show, by speaker number (set on the transcript's container).
+private struct SpeakerNamesKey: EnvironmentKey { static let defaultValue: [Int: String] = [:] }
+extension EnvironmentValues {
+ var speakerNames: [Int: String] {
+ get { self[SpeakerNamesKey.self] }
+ set { self[SpeakerNamesKey.self] = newValue }
+ }
+}
+
+struct SpeakerTag: View {
+ let number: Int
+ @Environment(\.speakerNames) private var names
+ var body: some View {
+ HStack(spacing: 5) {
+ Circle().fill(SpeakerColor.ink(number)).frame(width: 6, height: 6)
+ Text(SpeakerLabels.label(number, names)).font(.system(size: 11, weight: .semibold)).foregroundStyle(SpeakerColor.ink(number))
+ }
+ }
+}
+
+/// A line from the other side whose voice isn't one of the people on show.
+struct UnknownSpeakerTag: View {
+ var body: some View {
+ HStack(spacing: 5) {
+ Circle().strokeBorder(Palette.tertiary, lineWidth: 1).frame(width: 6, height: 6)
+ Text("未识别").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.tertiary)
+ }
+ .help(L("没认出是谁:太短,或和已知的声音都不像"))
+ }
+}
+
+/// Above the transcript once voices are told apart: who is speaking, and a one-click way out. Each
+/// person opens `SpeakerEditor`: a popover in the records window; in the notes window (`editing`
+/// set) a card right below the row, since a popover in a panel that never activates the app closes
+/// as soon as it opens.
+struct SpeakerStrip: View {
+ @ObservedObject var model: AppModel
+ let session: Session
+ /// The notes window's voice being edited: the editor opens inline instead of as a popover.
+ var editing: Binding<Int?>? = nil
+ @State private var popover: Int?
+
+ var body: some View {
+ let numbers = SpeakerLabels.voiceNumbers(session.lines)
+ let names = SpeakerLabels.names(session)
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .top, spacing: 8) {
+ FlowLayout(spacing: 6) {
+ ForEach(numbers.sorted { $0.value < $1.value }, id: \.key) { voice, n in
+ let on = (editing?.wrappedValue ?? popover) == voice
+ Button {
+ if let editing { editing.wrappedValue = on ? nil : voice } else { popover = voice }
+ } label: {
+ HStack(spacing: 5) {
+ Circle().fill(on ? Color.white : SpeakerColor.ink(n)).frame(width: 6, height: 6)
+ Text(SpeakerLabels.label(n, names)).font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(on ? Color.white : SpeakerColor.ink(n))
+ }
+ .fixedSize()
+ .padding(.horizontal, 8).frame(height: 22)
+ .background(Capsule().fill(on ? SpeakerColor.ink(n) : SpeakerColor.ink(n).opacity(0.08)))
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .help(SpeakerLabels.guessed(session)[n].map { _ in L("Ling 从对话里认出,点一下可以改") } ?? L("改名字,或和别人合并"))
+ .popover(isPresented: Binding(get: { editing == nil && popover == voice }, set: { if !$0 { popover = nil } }), arrowEdge: .bottom) {
+ SpeakerEditor(model: model, namer: model.speakerNamer, sessionID: session.id, voice: voice) { popover = nil }
+ }
+ }
+ }
+ Spacer(minLength: 0)
+ Button { model.settings.speakerVoices = false } label: {
+ Text("不准?关掉").font(.system(size: 11)).foregroundStyle(Palette.secondary).underline().fixedSize()
+ }
+ .buttonStyle(.plain)
+ .frame(height: 22)
+ .help(L("关掉说话人识别,记录里的名字一起收起"))
+ }
+ if let editing, let voice = editing.wrappedValue, numbers[voice] != nil {
+ SpeakerEditor(model: model, namer: model.speakerNamer, sessionID: session.id, voice: voice, inline: true) {
+ editing.wrappedValue = nil
+ model.notesWindow.returnKeyboard()
+ }
+ .id(voice)
+ }
+ }
+ .onAppear { model.speakerNamer.guess(session.id) }
+ }
+}
+
+/// Correct one voice: its name (Ling's guess and people from 人名和术语 are a click away), or merge it
+/// into another voice. `inline` (the notes window): a click on a name or a merge applies at once.
+struct SpeakerEditor: View {
+ @ObservedObject var model: AppModel
+ @ObservedObject var namer: SpeakerNamer
+ let sessionID: String
+ let voice: Int
+ var inline = false
+ let close: () -> Void
+ @State private var draft = ""
+ @State private var allMerges = false
+ @FocusState private var typing: Bool
+
+ private var session: Session? { model.store.session(sessionID) }
+
+ 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)
+ let names = SpeakerLabels.names(s)
+ let guess = SpeakerLabels.guessed(s)[n]
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 6) {
+ Circle().fill(SpeakerColor.ink(n)).frame(width: 8, height: 8)
+ Text(SpeakerLabels.label(n, names)).font(.system(size: 14, weight: .bold))
+ Text("说了 \(s.lines.filter { $0.voice == voice }.count) 句").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ Spacer()
+ if inline {
+ Button(action: close) {
+ Image(systemName: "xmark").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
+ .frame(width: 24, height: 24).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain).help("收起").accessibilityLabel(L("收起"))
+ }
+ }
+ VStack(alignment: .leading, spacing: 6) {
+ Text("是谁").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
+ let picks = suggestions(s, names: names, number: n, guess: guess)
+ if !picks.isEmpty {
+ FlowLayout(spacing: 6) {
+ ForEach(picks, id: \.self) { name in
+ choice(name, dark: name == names[n]) {
+ if inline { apply(s, guess, name) } else { draft = name }
+ }
+ }
+ }
+ }
+ HStack(spacing: 8) {
+ TextField(L("输入名字"), text: $draft).textFieldStyle(.roundedBorder)
+ .focused($typing)
+ .onSubmit { apply(s, guess, draft) }
+ .onExitCommand { close() }
+ if inline, typing || draft != (names[n] ?? "") {
+ SoftButton(L("保存"), dark: true) { apply(s, guess, draft) }
+ }
+ }
+ if inline && typing {
+ // The panel holds the keyboard only while a name is typed; Return or Esc gives it back.
+ Text("键盘暂时在这里,会议软件收不到 · 回车保存 · Esc 交还")
+ .font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk)
+ .fixedSize(horizontal: false, vertical: true)
+ } else if let guess {
+ HStack(alignment: .top, spacing: 8) {
+ Text(guess.evidence.isEmpty ? L("Ling 从对话里认出") : L("Ling 从对话里认出:\(guess.evidence)"))
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(2)
+ Spacer(minLength: 6)
+ Button(L("不是 TA")) {
+ model.renameSpeaker(session: s.id, voice: voice, "")
+ close()
+ }
+ .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.secondary)
+ }
+ } else if namer.busy.contains(s.id) {
+ Text("Ling 正在从对话里找名字…").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ let others = numbers.filter { $0.key != voice }.sorted { $0.value < $1.value }
+ if !others.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("其实是同一个人").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
+ FlowLayout(spacing: 6) {
+ ForEach(allMerges ? others : Array(others.prefix(3)), id: \.key) { other, on in
+ choice(L("并入 \(SpeakerLabels.label(on, names))")) {
+ model.mergeSpeaker(session: s.id, voice, into: other)
+ close()
+ }
+ }
+ if others.count > 3 && !allMerges {
+ choice(L("更多")) { allMerges = true }
+ }
+ }
+ }
+ }
+ if !inline {
+ HStack(spacing: 8) {
+ Spacer()
+ SoftButton(L("取消")) { close() }
+ SoftButton(L("完成"), dark: true) { apply(s, guess, draft) }
+ }
+ }
+ }
+ .padding(inline ? 14 : 16)
+ .frame(width: inline ? nil : 320)
+ .frame(maxWidth: inline ? .infinity : nil, alignment: .leading)
+ .background {
+ if inline {
+ RoundedRectangle(cornerRadius: 14).fill(Color.white)
+ .shadow(color: .black.opacity(0.08), radius: 10, y: 4)
+ .overlay(RoundedRectangle(cornerRadius: 14).stroke(Palette.line, lineWidth: 1))
+ }
+ }
+ .onAppear { draft = names[n] ?? "" }
+ }
+ }
+
+ private func choice(_ title: String, dark: Bool = false, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Text(title).font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(dark ? Color.white : Palette.ink)
+ .padding(.horizontal, 10).frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 8).fill(dark ? Palette.ink : Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(dark ? Palette.ink : Palette.line, lineWidth: 1))
+ .fixedSize()
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+
+ /// Ling's guess first, then people the notes mention, without names other voices already have.
+ private func suggestions(_ s: Session, names: [Int: String], number: Int, guess: VoiceGuess?) -> [String] {
+ let taken = Set(names.filter { $0.key != number }.values)
+ var out: [String] = []
+ if let g = s.voiceGuesses?[String(voice)]?.name ?? guess?.name { out.append(g) }
+ for t in NoteTerm.people(s.notes?.terms ?? []) where !out.contains(t) && !taken.contains(t) { out.append(t) }
+ if let mine = names[number], !out.contains(mine) { out.insert(mine, at: 0) }
+ return Array(out.prefix(4))
+ }
+
+ /// Keeping Ling's name stores nothing, so a later, better guess can still replace it.
+ private func apply(_ s: Session, _ guess: VoiceGuess?, _ typed: String) {
+ let name = typed.trimmingCharacters(in: .whitespacesAndNewlines)
+ if let guess, name == guess.name { model.renameSpeaker(session: s.id, voice: voice, nil) }
+ else if s.voiceNames?[String(voice)] != nil || !name.isEmpty { model.renameSpeaker(session: s.id, voice: voice, name) }
+ close()
+ }
+}
+
+/// "这句是谁说的": the people on show, the ones speaking just before and after first. Picked → done.
+struct LineSpeakerPicker: View {
+ /// Voice → speaker number, for the voices on show.
+ let voices: [Int: Int]
+ let current: Int?
+ let nearby: [Int]
+ let several: Bool
+ let pick: (Int) -> Void
+ @Environment(\.speakerNames) private var names
+
+ var body: some View {
+ let order = voices.keys.sorted { a, b in
+ let ia = nearby.firstIndex(of: a) ?? Int.max, ib = nearby.firstIndex(of: b) ?? Int.max
+ return ia != ib ? ia < ib : voices[a]! < voices[b]!
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ Text(several ? "这段是谁说的" : "这句是谁说的").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
+ FlowLayout(spacing: 6) {
+ ForEach(order, id: \.self) { v in
+ let n = voices[v]!
+ Button { pick(v) } label: {
+ HStack(spacing: 5) {
+ Circle().fill(SpeakerColor.ink(n)).frame(width: 6, height: 6)
+ Text(SpeakerLabels.label(n, names)).font(.system(size: 12, weight: .semibold)).foregroundStyle(SpeakerColor.ink(n))
+ }
+ .padding(.horizontal, 9).frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 8).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(v == current ? SpeakerColor.ink(n) : Palette.line, lineWidth: 1))
+ .fixedSize()
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ }
+ }
+}
+
+/// "说话人 6 已改成 David · 撤销", for a few seconds after a speaker edit.
+struct SpeakerUndoToast: View {
+ @ObservedObject var model: AppModel
+ let session: String?
+
+ var body: some View {
+ if let u = model.speakerUndo, u.session == session, !u.text.isEmpty {
+ HStack(spacing: 14) {
+ Text(u.text).font(.system(size: 13)).foregroundStyle(.white).lineLimit(2)
+ Button("撤销") { model.undoSpeakerEdit() }
+ .buttonStyle(.plain).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.accentPale)
+ }
+ .padding(.horizontal, 14).frame(minHeight: 38)
+ .background(RoundedRectangle(cornerRadius: 10).fill(Palette.ink).shadow(color: .black.opacity(0.2), radius: 12, y: 6))
+ .padding(.bottom, 18)
+ .transition(.opacity)
+ }
+ }
+}
+
+/// Debug render (`speakersRender`): the people row and the first lines, labelled as the transcript
+/// labels them (a name only where the speaker changes).
+struct SpeakerPreview: View {
+ @ObservedObject var model: AppModel
+ let session: Session
+ var body: some View {
+ let numbers = SpeakerLabels.numbers(session.lines)
+ let starts = SpeakerLabels.runStarts(session.lines, numbers)
+ VStack(alignment: .leading, spacing: 10) {
+ if !numbers.isEmpty { SpeakerStrip(model: model, session: session) }
+ ForEach(session.lines.prefix(12)) { l in
+ VStack(alignment: .leading, spacing: 3) {
+ if !starts.contains(l.id) {
+ } else if l.speaker == "me" { Text("你").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk) }
+ else if let n = numbers[l.id] { SpeakerTag(number: n) }
+ else if !numbers.isEmpty { UnknownSpeakerTag() }
+ Text(l.src).font(.system(size: 13)).foregroundStyle(Palette.ink)
+ }
+ }
+ }
+ .padding(16)
+ }
+}
diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swift
index 7587345..175f192 100644
--- a/Sources/LiveSubs/Translator.swift
+++ b/Sources/LiveSubs/Translator.swift
@@ -1,7 +1,5 @@
-import AppKit
import AVFoundation
import AudioToolbox
-import CoreAudio
import CoreMedia
import Speech
import Translation
diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swift
index c32880f..248c5a8 100644
--- a/Sources/LiveSubs/Views.swift
+++ b/Sources/LiveSubs/Views.swift
@@ -770,7 +770,7 @@ struct MainWindowView: View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
// The newest day shows; older ones fold under one row until asked for (or searched).
- let all = groups
+ let all = RecordList.groups(filtered)
let folded = query.isEmpty && !showOlder && all.count > 1
ForEach(Array((folded ? Array(all.prefix(1)) : all).enumerated()), id: \.element.title) { i, g in
Text(g.title).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)
@@ -803,27 +803,10 @@ struct MainWindowView: View {
.padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 14)
.onChange(of: selection) { _, id in
// A meeting picked from elsewhere (search, the notes window) shouldn't hide in a fold.
- if let id, let first = groups.first, !first.sessions.contains(where: { $0.id == id }) { showOlder = true }
+ if let id, let first = RecordList.groups(filtered).first, !first.sessions.contains(where: { $0.id == id }) { showOlder = true }
}
}
- /// 今天 / 昨天 / 本周 / then one group per month, newest first.
- private var groups: [(title: String, sessions: [Session])] {
- let cal = Calendar.current
- var out: [(title: String, sessions: [Session])] = []
- for s in filtered {
- let d = s.startedAt
- let title: String
- if cal.isDateInToday(d) { title = L("今天") }
- else if cal.isDateInYesterday(d) { title = L("昨天") }
- else if cal.isDate(d, equalTo: Date(), toGranularity: .weekOfYear) { title = L("本周") }
- else if cal.isDate(d, equalTo: Date(), toGranularity: .year) { title = dateText(d, "MMMM") }
- else { title = dateText(d, "yMMMM") }
- if out.last?.title == title { out[out.count - 1].sessions.append(s) } else { out.append((title, [s])) }
- }
- return out
- }
-
private func sessionRow(_ s: Session) -> some View {
let selected = s.id == (selection ?? store.sessions.first?.id)
let live = s.id == store.liveID
@@ -844,7 +827,7 @@ struct MainWindowView: View {
Image(systemName: "mic").font(.system(size: 11)).foregroundStyle(Palette.secondary)
.help(L("会议室"))
}
- Text(Self.untitled(s) ? L("未命名会议") : Self.listTitle(s))
+ Text(RecordList.untitled(s) ? L("未命名会议") : RecordList.listTitle(s))
.font(.system(size: 13, weight: selected ? .semibold : .regular))
.foregroundStyle(selected || live ? Palette.ink : Palette.secondary).lineLimit(1)
Spacer(minLength: 0)
@@ -855,7 +838,7 @@ struct MainWindowView: View {
.shadow(color: selected ? Palette.ink.opacity(0.06) : .clear, radius: 1.5, y: 1))
.contentShape(Rectangle())
}
- .help(live ? L("正在记录") : [when(s), Self.length(s)].joined(separator: " · "))
+ .help(live ? L("正在记录") : [RecordList.when(s), RecordList.length(s)].joined(separator: " · "))
.buttonStyle(.plain)
.contextMenu {
if let path = s.sourcePath, FileManager.default.fileExists(atPath: path) {
@@ -894,55 +877,6 @@ struct MainWindowView: View {
}
}
- private func when(_ s: Session) -> String {
- let cal = Calendar.current
- return dateText(s.startedAt, cal.isDateInToday(s.startedAt) || cal.isDateInYesterday(s.startedAt) ? "HHmm"
- : cal.isDate(s.startedAt, equalTo: Date(), toGranularity: .weekOfYear) ? "EEE" : "MMMd")
- }
-
- /// Notes titles often start with the day ("11月2日 产品周会"); under a 今天 heading that only
- /// pushes the real title out of the row.
- static func listTitle(_ s: Session) -> String {
- let title = s.displayTitle
- for prefix in [dateText(s.startedAt, "MMMd"), dateText(s.startedAt, "MMMMd")] where title.hasPrefix(prefix) {
- let rest = title.dropFirst(prefix.count).trimmingCharacters(in: .whitespaces)
- if !rest.isEmpty { return rest }
- }
- return title
- }
-
- /// Still on the stored "会议 <date>" title: not renamed, and no notes title to show.
- static func untitled(_ s: Session) -> Bool {
- !(s.renamed ?? !s.title.hasPrefix("会议 ")) && (s.notes?.title ?? "").isEmpty && s.sourceFile == nil
- }
-
- static func length(_ s: Session) -> String {
- let mins = Int(s.duration / 60)
- if mins < 1 { return L("不到 1 分钟") }
- return mins < 60 ? L("\(mins) 分钟") : mins % 60 == 0 ? L("\(mins / 60) 小时") : L("\(mins / 60) 小时 \(mins % 60) 分")
- }
-
- /// "英 → 中" (short) or "英语 → 中文", from the most common pair among the lines.
- static func pair(_ s: Session, short: Bool) -> String? {
- let pairs = Dictionary(grouping: s.lines.filter { $0.speaker != "me" }, by: { "\(lang($0.srcLang))|\(lang($0.dstLang))" })
- guard let top = pairs.max(by: { $0.value.count < $1.value.count })?.key else { return nil }
- let p = top.split(separator: "|").map(String.init)
- guard p.count == 2, p[0] != p[1] else { return nil }
- func name(_ c: String) -> String {
- let names = ["en": L("英语"), "ja": L("日语"), "zh-CN": L("中文"), "zh-TW": L("繁中"), "ko": L("韩语"),
- "es": L("西语"), "fr": L("法语"), "de": L("德语"), "pt": L("葡语")]
- guard let n = names[c] else { return c.uppercased() }
- guard short else { return n }
- return uiIsChinese ? String(n.prefix(1)) : c == "zh-TW" ? "ZH-TW" : String(c.prefix(2)).uppercased()
- }
- return "\(name(p[0])) → \(name(p[1]))"
- }
-
- private static func lang(_ code: String) -> String {
- let base = String(code.split(whereSeparator: { $0 == "-" || $0 == "_" }).first ?? "")
- return base == "zh" ? (code.contains("Hant") || code.hasSuffix("TW") || code.hasSuffix("HK") ? "zh-TW" : "zh-CN") : base
- }
-
// MARK: Detail
@ViewBuilder
@@ -1099,19 +1033,19 @@ struct MainWindowView: View {
let live = s.id == store.liveID
let notes = live ? model.notes.notes : s.notes
// When and how long up front; the languages and notes version wait in the tooltip.
- let more = [Self.pair(s, short: false),
+ let more = [RecordList.pair(s, short: false),
notes.flatMap { $0.isEmpty ? nil : ($0.final ? L("完整版纪要") : L("速记版纪要")) }]
return VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 8) {
if live { Tag(L("正在记录"), live: true) }
- Text(([dateText(s.startedAt, "MMMdHHmm"), Self.length(s)] + (s.sourceFile.map { [$0, L("导入")] } ?? [])
+ Text(([dateText(s.startedAt, "MMMdHHmm"), RecordList.length(s)] + (s.sourceFile.map { [$0, L("导入")] } ?? [])
+ (s.room == true ? [L("会议室")] : [])).joined(separator: " · "))
.font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary).lineLimit(1)
.help(([dateLine(s, live: live)] + more.compactMap { $0 }).joined(separator: " · "))
}
TextField("标题", text: Binding(
// The date is on the line above; a notes title that starts with it shows without.
- get: { titleDraft.isEmpty ? Self.listTitle(s) : titleDraft },
+ get: { titleDraft.isEmpty ? RecordList.listTitle(s) : titleDraft },
set: { titleDraft = $0 }
), axis: .vertical)
.textFieldStyle(.plain)
@@ -1290,7 +1224,6 @@ struct MainWindowView: View {
}
}
-
extension MainWindowView {
/// "这句是谁说的": the people on show; the line takes that voice.
@ViewBuilder
diff --git a/Sources/LiveSubs/Voices.swift b/Sources/LiveSubs/Voices.swift
index 312f665..85c68a5 100644
--- a/Sources/LiveSubs/Voices.swift
+++ b/Sources/LiveSubs/Voices.swift
@@ -244,6 +244,9 @@ enum VoiceReference {
}
}
+#if !CICADA_IOS
+// Mac app only (the iOS build sets CICADA_IOS): pinned to a Mac input device and checked with the
+// Mac recognizer. iOS records its own (docs/ios-plan.md, M3).
/// Records the microphone for the voice clone: 16 kHz mono into a temporary WAV, with a level for
/// the meter. Stops by itself at 30 s.
@MainActor
@@ -373,3 +376,4 @@ final class VoiceRecorder: ObservableObject {
return await LoopbackTest.transcribe([buf], locale: locale)
}
}
+#endif
diff --git a/Tests/LiveSubsTests/ImportTests.swift b/Tests/LiveSubsTests/ImportTests.swift
index 84ce4c1..6e05221 100644
--- a/Tests/LiveSubsTests/ImportTests.swift
+++ b/Tests/LiveSubsTests/ImportTests.swift
@@ -27,7 +27,7 @@ import Testing
var s = Session(id: "i", title: Session.defaultTitle(Date()), startedAt: Date(), endedAt: nil, lines: [], hasAudio: false)
s.sourceFile = "客户访谈.m4a"
#expect(s.displayTitle == "客户访谈")
- #expect(!MainWindowView.untitled(s))
+ #expect(!RecordList.untitled(s))
s.renamed = true
s.title = "Renamed"
#expect(s.displayTitle == "Renamed")