知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix: while Ling listens in place of a speech model, hold music, ringtones and alerts are no longer sent to it
wqugurue31f1223bed8
diff --git a/Sources/Cicada/CloudHearing.swift b/Sources/Cicada/CloudHearing.swiftindex 929fa56..dd6c3ea 100644--- a/Sources/Cicada/CloudHearing.swift+++ b/Sources/Cicada/CloudHearing.swift@@ -328,8 +328,13 @@ final class CloudStream: RecognitionStream, @unchecked Sendable {continuation.finish()}- /// On `queue`.+ /// On `queue`. A stretch nobody spoke in (hold music, a ringtone, an alert) isn't sent: Ming+ /// would write something for it anyway, and a minute on hold is some thirty calls.private func send(_ piece: CloudSegmenter.Piece) {+ if let v = SoundKind.judge(piece.samples), v.speech < SoundKind.speechLine {+ debugLog(String(format: "hear: not speech, not sent (speech %.2f, music %.2f, %.1f s)", v.speech, v.music, piece.seconds))+ return+ }issued += 1let index = issuedlet wav = CloudHearing.wav(piece.samples)diff --git a/Sources/Cicada/SoundKind.swift b/Sources/Cicada/SoundKind.swiftnew file mode 100644index 0000000..f59cbe5--- /dev/null+++ b/Sources/Cicada/SoundKind.swift@@ -0,0 +1,61 @@+import AVFoundation+import SoundAnalysis++/// Whether a stretch of audio has anyone speaking in it, by the system's own sound classifier+/// (SoundAnalysis, on the device, nothing bundled). Loudness can't tell hold music, a ringtone or an+/// alert from a voice; this can, in 1 s windows: speech scores 0.8–0.98, music and alerts under 0.05,+/// and talk over music keeps its speech score (both labels are given).+enum SoundKind {+ struct Verdict: Equatable {+ /// The highest speech confidence of any window: one spoken second is enough.+ var speech: Double+ var music: Double+ }++ /// Below this nobody spoke in any window (`VADEval` measures it on `scripts/vad-clips.py`).+ static let speechLine = 0.3+ static let window = 1.0+ static let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)!++ private final class Observer: NSObject, SNResultsObserving {+ var verdict = Verdict(speech: 0, music: 0)+ var windows = 0+ func request(_ request: SNRequest, didProduce result: SNResult) {+ guard let c = result as? SNClassificationResult else { return }+ windows += 1+ verdict.speech = max(verdict.speech, c.classification(forIdentifier: "speech")?.confidence ?? 0)+ verdict.music = max(verdict.music, c.classification(forIdentifier: "music")?.confidence ?? 0)+ }+ }++ /// 16 kHz mono samples; nil when the classifier can't be had (then the caller treats it as speech).+ /// A stretch shorter than a window is padded with silence to one.+ static func judge(_ samples: [Float]) -> Verdict? {+ guard !samples.isEmpty else { return nil }+ let frames = max(samples.count, Int(window * 16000))+ guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)),+ let dst = buffer.floatChannelData?[0] else { return nil }+ buffer.frameLength = AVAudioFrameCount(frames)+ dst.update(repeating: 0, count: frames)+ samples.withUnsafeBufferPointer { dst.update(from: $0.baseAddress!, count: samples.count) }+ do {+ let request = try SNClassifySoundRequest(classifierIdentifier: .version1)+ request.windowDuration = CMTime(seconds: window, preferredTimescale: 16000)+ request.overlapFactor = 0.5+ let analyzer = SNAudioStreamAnalyzer(format: format)+ let observer = Observer()+ try analyzer.add(request, withObserver: observer)+ // The stream analyzer reports on this thread, before these return.+ analyzer.analyze(buffer, atAudioFramePosition: 0)+ analyzer.completeAnalysis()+ return observer.windows > 0 ? observer.verdict : nil+ } catch {+ debugLog("sound kind: \(error.localizedDescription)")+ return nil+ }+ }++ static func judge(_ samples: [Int16]) -> Verdict? {+ judge(samples.map { Float($0) / 32768 })+ }+}diff --git a/Tests/CicadaTests/SoundKindTests.swift b/Tests/CicadaTests/SoundKindTests.swiftnew file mode 100644index 0000000..40d8c5c--- /dev/null+++ b/Tests/CicadaTests/SoundKindTests.swift@@ -0,0 +1,64 @@+import Foundation+import Testing+@testable import Cicada++/// `SoundKind` in front of Ming, on the evaluation clips (see `VADEval`).+extension VADEval {+ /// 16 kHz Int16, as `CloudStream` gets it (three-sample average: enough for an evaluation).+ static func int16k(_ clip: Clip) -> [Int16] {+ let k = Int(clip.rate / 16000)+ return stride(from: 0, to: clip.samples.count - k + 1, by: k).map { i in+ var v: Float = 0+ for j in 0..<k { v += clip.samples[i + j] }+ return Int16(max(-1, min(1, v / Float(k))) * 32767)+ }+ }++ /// What `CloudStream` would send Ming, with and without `SoundKind`: stretches with speech in them+ /// that it would drop (must be none), and stretches without that it saves.+ @Test func cloudGate() throws {+ let clips = try Self.load()+ try #require(!clips.isEmpty)+ var out = "clip pieces speech sent-noise dropped-noise DROPPED-SPEECH ms/piece (speech/music of each dropped)\n"+ var lost = 0, saved = 0, wasted = 0+ for clip in clips where !clip.room {+ let samples = Self.int16k(clip)+ var seg = CloudSegmenter()+ var pieces: [CloudSegmenter.Piece] = []+ seg.feed(samples) { pieces.append($0) }+ seg.flush { pieces.append($0) }+ var speechN = 0, sentNoise = 0, droppedNoise = 0, droppedSpeech = 0, ms = 0.0, notes: [String] = []+ for p in pieces {+ let overlap = clip.speech.reduce(0.0) { $0 + max(0, min($1.1, p.start + p.seconds) - max($1.0, p.start)) }+ let hasSpeech = overlap >= 0.2+ if hasSpeech { speechN += 1 }+ let t0 = Date()+ let v = SoundKind.judge(p.samples)+ ms += Date().timeIntervalSince(t0) * 1000+ let drop = v.map { $0.speech < SoundKind.speechLine } ?? false+ if drop {+ notes.append(String(format: "%.2f/%.2f", v!.speech, v!.music))+ if hasSpeech { droppedSpeech += 1 } else { droppedNoise += 1 }+ } else if !hasSpeech {+ sentNoise += 1+ notes.append(String(format: "sent %.2f/%.2f", v?.speech ?? -1, v?.music ?? -1))+ }+ }+ lost += droppedSpeech; saved += droppedNoise; wasted += sentNoise+ out += String(format: "%-20@ %6d %6d %10d %13d %14d %8.0f %@\n", clip.name as NSString, pieces.count, speechN,+ sentNoise, droppedNoise, droppedSpeech, ms / Double(max(1, pieces.count)),+ notes.joined(separator: " ") as NSString)+ }+ // The shortest stretches: the start of each clip's first line, cut short.+ for clip in clips where !clip.room {+ let samples = Self.int16k(clip)+ let a = Int(clip.speech[0].0 * 16000)+ let v = [0.3, 0.5, 0.7].map { SoundKind.judge(Array(samples[a..<(a + Int($0 * 16000))]))?.speech ?? -1 }+ out += String(format: "short %-20@ 0.3 s %.2f 0.5 s %.2f 0.7 s %.2f\n", clip.name as NSString, v[0], v[1], v[2])+ }+ out += "\nTOTAL dropped with speech \(lost), noise dropped \(saved), noise still sent \(wasted)\n"+ print(out)+ try out.write(toFile: ProcessInfo.processInfo.environment["CICADA_VAD_EVAL"]! + "/cloud.txt", atomically: true, encoding: .utf8)+ #expect(lost == 0)+ }+}diff --git a/ios/shared-sources.txt b/ios/shared-sources.txtindex e200df8..fc31dc9 100644--- a/ios/shared-sources.txt+++ b/ios/shared-sources.txt@@ -18,3 +18,4 @@ Sources/Cicada/RecordList.swiftSources/Cicada/Languages.swiftSources/Cicada/Recognition.swiftSources/Cicada/CloudHearing.swift+Sources/Cicada/SoundKind.swiftdiff --git a/site/changelog.json b/site/changelog.jsonindex 0c744e7..3d6c087 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -139,6 +139,14 @@],"title": "会议里有人敲键盘,不再被当成有人在说话。","text": "一下下的按键声会打断静音,知了等不到停顿:换语言的判断和会议结束的提示都会推迟。"+ },+ {+ "kind": "improved",+ "platforms": [+ "mac"+ ],+ "title": "先用 Ling 听时,等待音乐、铃声和提示音不再发给 Ling。",+ "text": "发出去之前先用 macOS 自带的声音分类听一下有没有人说话;被晾在等待音乐里一分钟,原来要白白调用 Ling 三十来次。"}]},