知了 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: fast speech without pauses comes out one sentence or clause per line instead of one growing block (#20)
wquguru93dfb075e933
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 0b8cffe..0becd4b 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -1521,7 +1521,7 @@ final class AppModel: ObservableObject {prev.seg.clock == seg.clock, prev.seg.sourceCode == seg.sourceCode,// macOS 14/15: the older recognizer ends a line only at a real pause and often drops// the full stop, so a missing one says nothing; only a line Cicada cut is a half sentence.- !Recognition.legacy || prev.seg.cut,+ !Recognition.legacy || prev.seg.cut, !prev.seg.split,HeardText.continues(prev.seg.text, seg.text, gap: seg.start - prev.seg.end, cut: prev.seg.cut) else {appendHeard(seg, t: t, tag: true)return@@ -1559,6 +1559,7 @@ final class AppModel: ObservableObject {joined.text = textjoined.end = seg.endjoined.cut = seg.cut+ joined.split = seg.splitlastHeard = (joined, prev.line)store.setSource(lineID: prev.line, text)if let id = store.liveID { fixes.applyKnown(lineID: prev.line, in: id) }diff --git a/Sources/Cicada/HeardText.swift b/Sources/Cicada/HeardText.swiftindex f11b8b9..60e1eeb 100644--- a/Sources/Cicada/HeardText.swift+++ b/Sources/Cicada/HeardText.swift@@ -1,4 +1,5 @@import Foundation+import NaturalLanguage/// The other side's finished lines before they are recorded and translated: tidied, and joined to the/// line before when a pause cut one sentence in two.@@ -48,10 +49,139 @@ enum HeardText {return tail.filter { $0.isASCII && $0.isLetter }.count >= 15}+ /// A draft that has just reached the end of a sentence: it ends in 。/./?/!, and is long enough+ /// to be a line of its own (12 Chinese or Japanese characters, 5 words). The recognizer writes+ /// the mark the moment the sentence's last word is heard, so that draft's end is where the+ /// sentence ends: fast speech with no pause between sentences (issue #20) is ended there.+ static func endsSentence(_ draft: String) -> Bool {+ let t = draft.trimmingCharacters(in: .whitespaces)+ // "..." and "…" trail off; "3." is a number being read.+ guard let last = t.last, "。!?.!?".contains(last), !t.hasSuffix(".."),+ !(last == "." && t.dropLast().last?.isNumber == true) else { return false }+ let cjk = t.unicodeScalars.contains { $0.properties.isIdeographic || (0x3040...0x30FF).contains($0.value) }+ return cjk ? t.filter(\.isLetter).count >= 12 : t.split(separator: " ").count >= 5+ }++ /// A line ended at a sentence comes back running into the next one ("…思います。前回こちらの"):+ /// the draft's end trails its words by the recognizer's lag. Split at the last sentence end, when+ /// the head is a line of its own and the tail has words; the tail starts the next line.+ static func splitAtSentenceEnd(_ text: String) -> (head: String, tail: String)? {+ var i = text.endIndex+ while i > text.startIndex {+ i = text.index(before: i)+ let head = String(text[...i])+ guard "。!?.!?".contains(text[i]), endsSentence(head) else { continue }+ let tail = text[text.index(after: i)...].trimmingCharacters(in: .whitespaces)+ guard tail.contains(where: \.isLetter) else { return nil }+ return (head.trimmingCharacters(in: .whitespaces), tail)+ }+ return nil+ }++ /// Where a long line may be ended when no sentence end comes: Chinese recognition writes almost+ /// no 。 (4% of drafts in a fast review) but often a ,, so a line runs on for 10 s and 80 chars.+ enum Boundary: Int, Comparable {+ /// Between two words: only for a line past `capped`.+ case word+ /// After a comma, before a Chinese connective (所以, 但是…) or after a final particle (吧, 呢…).+ case clause+ case sentence+ static func < (a: Boundary, b: Boundary) -> Bool { a.rawValue < b.rawValue }+ }++ /// Chinese words that start a clause, and particles that end one.+ static let connectives: Set<String> = ["所以", "但是", "因为", "然后", "可是", "而且", "不过", "其实", "反正",+ "如果", "虽然", "或者", "另外", "接下来", "总之", "因此", "于是", "就是说"]+ static let particles: Set<String> = ["吧", "呢", "吗", "啊", "嘛", "呀", "啦"]++ static func isCJK(_ text: String) -> Bool {+ text.unicodeScalars.contains { $0.properties.isIdeographic || (0x3040...0x30FF).contains($0.value) }+ }++ /// How long a piece is: Chinese or Japanese characters, or words.+ static func size(_ text: String) -> Int {+ isCJK(text) ? text.filter(\.isLetter).count : text.split(whereSeparator: \.isWhitespace).count+ }++ /// A line this long gets a clause cut (`clause`) or, past `capped`, a cut between words.+ static func clauseFrom(_ code: String) -> Int { code.hasPrefix("zh") ? 24 : (code == "ja" ? 40 : 20) }+ static func capped(_ code: String) -> Int { ["zh", "ja"].contains(where: code.hasPrefix) ? 60 : 25 }++ /// Every place in `text` a new line could start, as a character offset, with its kind.+ static func boundaries(_ text: String, language code: String) -> [(at: Int, kind: Boundary)] {+ var out: [Int: Boundary] = [:]+ func add(_ at: Int, _ kind: Boundary) {+ guard at > 0, at < text.count else { return }+ out[at] = max(out[at] ?? kind, kind)+ }+ let commas: Set<Character> = code.hasPrefix("zh") ? [",", ","] : (code == "ja" ? ["、", ","] : [","])+ for (i, ch) in text.enumerated() {+ if "。!?!?".contains(ch) || (ch == "." && i + 1 < text.count) { add(i + 1, .sentence) }+ if commas.contains(ch) { add(i + 1, .clause) }+ }+ let tokenizer = NLTokenizer(unit: .word)+ tokenizer.string = text+ if code.hasPrefix("zh") { tokenizer.setLanguage(.simplifiedChinese) }+ var starts = Set<Int>()+ tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { range, _ in+ let start = text.distance(from: text.startIndex, to: range.lowerBound)+ starts.insert(start)+ add(start, .word)+ if code.hasPrefix("zh"), particles.contains(String(text[range])) {+ add(text.distance(from: text.startIndex, to: range.upperBound), .clause)+ }+ return true+ }+ if code.hasPrefix("zh") {+ // The tokenizer may split a connective ("所" "以"): it counts when it starts and ends on+ // word boundaries, so one inside a longer word does not.+ let chars = Array(text)+ var found: [Int: Int] = [:]+ for p in starts {+ for c in connectives where p + c.count <= chars.count && String(chars[p..<(p + c.count)]) == c+ && (starts.contains(p + c.count) || p + c.count == chars.count) {+ found[p] = c.count+ }+ }+ // "因为如果…" starts one clause: only the first of two connectives in a row.+ for p in found.keys where !found.contains(where: { $0.key + $0.value == p }) { add(p, .clause) }+ // Nor is a word gap inside one ("所" | "以").+ for (p, n) in found { for i in (p + 1)..<(p + n) where out[i] == .word { out[i] = nil } }+ }+ // Spaces belong to the line before: a boundary sits after them.+ return out.keys.sorted().map { at in+ var a = at+ while a < text.count, text[text.index(text.startIndex, offsetBy: a)].isWhitespace { a += 1 }+ return (a, out[at]!)+ }+ }++ /// A line Cicada ended at a clause or between words comes back running on past it: split it at+ /// the boundary of at least `kind` nearest `near` (the draft's head when the cut was asked for).+ /// The final may drop the draft's comma: then the word gap nearest the cut.+ static func split(_ text: String, near: Int, kind: Boundary, language code: String) -> (head: String, tail: String)? {+ if let s = split(text, near: near, kind: kind, within: max(8, near / 3), language: code) { return s }+ return kind > .word ? split(text, near: near, kind: .word, within: 3, language: code) : nil+ }++ private static func split(_ text: String, near: Int, kind: Boundary, within: Int,+ language code: String) -> (head: String, tail: String)? {+ let fit = boundaries(text, language: code).filter { b in+ guard b.kind >= kind, abs(b.at - near) <= within else { return false }+ let head = String(text.prefix(b.at)), tail = String(text.dropFirst(b.at))+ return size(head) >= (isCJK(head) ? 12 : 5) && tail.contains(where: \.isLetter)+ }+ guard let best = fit.min(by: { (abs($0.at - near), -$0.kind.rawValue) < (abs($1.at - near), -$1.kind.rawValue) }) else { return nil }+ let head = text.prefix(best.at).trimmingCharacters(in: .whitespaces)+ let tail = text.dropFirst(best.at).trimmingCharacters(in: .whitespaces)+ return (head, tail)+ }+/// The longest pause, in seconds, that still joins two pieces of one sentence.static let joinGap = 1.5/// A line this long takes nothing more: past it a translation is slow and the line hard to read.- /// The piece that finishes a shorter line always joins it, so a sentence is never left half.+ /// The piece that finishes a shorter line joins it, unless in Chinese or Japanese the two would+ /// pass `capped`: that long a line is ended at a clause or word anyway.static let joinWords = 40/// Whether `next` carries on `previous`, from the same voice, rather than starting a sentence.@@ -63,6 +193,8 @@ enum HeardText {let cjk = previous.unicodeScalars.contains { $0.properties.isIdeographic }let size = cjk ? previous.count / 2 : previous.split(separator: " ").countguard size < joinWords else { return false }+ // Three pieces of fast Japanese joined into 113 characters (issue #20).+ if isCJK(previous + next), Self.size(previous + next) > capped("zh") { return false }switch last {case "?", "!", "?", "!": return falsecase ".", "。": return cut && first.isLowercasediff --git a/Sources/Cicada/ListenEngine.swift b/Sources/Cicada/ListenEngine.swiftindex 7ce6bba..623bfab 100644--- a/Sources/Cicada/ListenEngine.swift+++ b/Sources/Cicada/ListenEngine.swift@@ -14,6 +14,8 @@ struct Segment {/// and whether Cicada ended it at a pause: what deciding a join needs (`HeardText.continues`).var start = 0.0, end = 0.0, clock = 0var cut = false+ /// Cicada ended it where a sentence or clause ends, on purpose: the next line doesn't join it.+ var split = false/// The record's own recognizer heard it too and will settle its words (`onRefined`).var refining = false}@@ -206,6 +208,26 @@ final class ListenEngine {private var lastCutThrough = 0.0/// A cut was asked for: the next final line ends at Cicada's pause, not the speaker's.private var cutAsked = false+ /// The last draft that ended a sentence and its audio time (`HeardText.endsSentence`), and the+ /// head of one a cut was asked to end at: the final is checked against that, not the whole draft.+ private var volatileSentence: (head: String, end: Double)?+ private var sentenceCutHead: String?+ /// Where the line in progress could end short of a sentence (`HeardText.boundaries`, offsets in+ /// `shownDraft`), each with the audio time of the draft it first showed in.+ private var seenBoundaries: [(at: Int, kind: HeardText.Boundary, end: Double)] = []+ /// The cut asked for ends there: the final is split at it.+ private var pendingSplit: (near: Int, kind: HeardText.Boundary)?+ /// When the last cut was asked for: the next waits for its line (a moment at most), or it+ /// would take the place the first one is to be split at.+ private var cutAskedAt = Date.distantPast+ /// What a line ended at a sentence ran on into the next one: it starts the next line, and the+ /// draft shows it in front (`HeardText.splitAtSentenceEnd`).+ private var carry: (text: String, start: Double)?+ /// The line in progress as shown: what was carried over, then the draft.+ private var shownDraft: String {+ guard let carry else { return volatileText }+ return [carry.text, volatileText].filter { !$0.isEmpty }.joined(separator: joiner(for: activeLang?.code ?? ""))+ }/// Final transcript time and how long after the last word it came, per segment, until its translation lands.private var finalTiming: [Int: (at: Date, recognize: Double?)] = [:]@@ -404,6 +426,7 @@ final class ListenEngine {// Lines still waiting for the language are recorded rather than dropped: the meeting// ended before detection settled it. Not when the only model said the audio isn't its// language: those lines are noise, and the recording keeps what was said.+ flushCarry()if settings.sourceMode == .auto, !recordable, !mismatch { flushUnconfirmed() }unconfirmed = []heardSpeech = isRunning && (router.stats().voicedTotal >= 3 || firstHeardAt != nil)@@ -430,6 +453,10 @@ final class ListenEngine {recognizer = nilsegments.removeAll()volatileText = ""+ volatileSentence = nil+ carry = nil+ seenBoundaries = []+ pendingSplit = nilvolatileTranslation = ""lastVolatileSent = ""volatileInFlight = false@@ -684,10 +711,15 @@ final class ListenEngine {}activeLang = langvolatileText = ""+ carry = nil+ seenBoundaries = []+ pendingSplit = nilvolatileTranslation = ""lastVolatileSent = ""volatileEpoch += 1cutAsked = false+ volatileSentence = nil+ sentenceCutHead = nil// The new transcriber's audio clock starts again at zero.lastCutThrough = 0onStateChange?()@@ -790,12 +822,31 @@ final class ListenEngine {if !text.isEmpty { lastWordsAt = Date(); onWords?() }if result.isFinal {text = HeardText.clean(text)- let fuller = HeardText.fuller(final: text, draft: volatileText)+ let fuller = HeardText.fuller(final: text, draft: sentenceCutHead ?? volatileText)+ let splitAt = pendingSplit+ pendingSplit = nil+ sentenceCutHead = nil+ volatileSentence = nil+ seenBoundaries = []if fuller != text {debugLog("final dropped words the draft had: kept the draft")contentLog("FINAL was: \(text)")text = fuller}+ var start = result.start, end = result.end+ if let c = carry {+ carry = nil+ text = HeardText.clean(c.text + joiner(for: activeLang?.code ?? "") + text)+ start = c.start+ }+ let code = activeLang?.code ?? ""+ if let at = splitAt, let split = at.kind == .sentence ? HeardText.splitAtSentenceEnd(text)+ : HeardText.split(text, near: at.near, kind: at.kind, language: code) {+ // Times shared out by length: the tail is a second or so of the next sentence.+ let at = start + (end - start) * Double(split.head.count) / Double(max(1, text.count))+ carry = (split.tail, at)+ (text, end) = (split.head, at)+ }volatileText = ""volatileEpoch += 1// A "." or "…" from a breath or a click is no sentence: Ling would answer it with a note that@@ -809,19 +860,20 @@ final class ListenEngine {let provisional = given ?? (volatileTranslation.isEmpty ? nil : volatileTranslation)var seg = Segment(id: nextSegmentID, text: text, sourceCode: result.language ?? activeLang?.code ?? "auto",translation: provisional)- seg.start = result.start- seg.end = result.end+ seg.start = start+ seg.end = endseg.clock = genseg.cut = cutAsked+ seg.split = splitAt != nilcutAsked = falseseg.refining = refiner != nilif refiner != nil { settled(refiner!.emitted(id: seg.id, start: seg.start, end: seg.end, text: seg.text)) }if settings.speakerVoices {- seg.voiceSamples = router.voiceSamples(from: result.start, to: result.end)+ seg.voiceSamples = router.voiceSamples(from: start, to: end)}nextSegmentID += 1// How long ago, in real time, the sentence's last word was spoken.- let ago = router.fedSeconds() - result.end+ let ago = router.fedSeconds() - endfinalTiming[seg.id] = (Date(), ago.isFinite && ago >= 0 && ago < 30 ? ago : nil)if finalTiming.count > 40, let oldest = finalTiming.keys.min() { finalTiming[oldest] = nil }var shown = seg@@ -833,7 +885,7 @@ final class ListenEngine {volatileTranslation = ""lastVolatileSent = ""contentLog(String(format: "FINAL conf=%.2f [%@] %@", conf, activeLang?.locale ?? "?", text))- let duration = max(0, result.end - result.start)+ let duration = max(0, end - start)// Only confirmed-language sentences go into the meeting record; earlier ones wait.let spoken = duration.isFinite ? duration : 0if recordable {@@ -860,7 +912,10 @@ final class ListenEngine {if firstHeardAt == nil, text.contains(where: \.isLetter) { firstHeardAt = Date() }if volatileText.isEmpty { volatileStartedAt = Date(); volatileStartClock = router.fedSeconds() }if text != volatileText { volatileChangedAt = Date() }+ // A sentence just ended: remember where, until words past it come to end the line there.+ if HeardText.endsSentence(text) { volatileSentence = (text, result.end) }volatileText = text+ noteBoundaries(at: result.end)checkForeignLetters(text)}renderSubtitles()@@ -879,10 +934,11 @@ final class ListenEngine {}private func renderSubtitles() {- guard !(segments.isEmpty && volatileText.isEmpty) else { return }+ let draft = shownDraft+ guard !(segments.isEmpty && draft.isEmpty) else { return }let srcJoin = joiner(for: activeLang?.code ?? "en")let last = segments.last.map { fixedText[$0.id] ?? $0.text } ?? ""- let source = [last, volatileText].filter { !$0.isEmpty }+ let source = [last, draft].filter { !$0.isEmpty }.joined(separator: srcJoin.isEmpty ? " " : srcJoin)if settings.sourceMode == .auto, !recordable {onSubtitle?(source, asksLanguage ? L("听不出是哪种语言,到菜单栏里选一下") : L("正在识别语言…"))@@ -1203,6 +1259,10 @@ final class ListenEngine {unconfirmed = []segments.removeAll()volatileText = ""+ volatileSentence = nil+ carry = nil+ seenBoundaries = []+ pendingSplit = nilvolatileTranslation = ""lastVolatileSent = ""mismatch = false@@ -1376,7 +1436,7 @@ final class ListenEngine {// A partial without a translation is fine while the AI service will translate the sentence.let coming = kind == .draft && translator?.ling.usable == trueif out == nil, !coming, segments.allSatisfy({ $0.translation == nil }) && volatileTranslation.isEmpty {- onSubtitle?(volatileText.isEmpty ? (segments.last?.text ?? "") : volatileText, L("翻译暂不可用"))+ onSubtitle?(shownDraft.isEmpty ? (segments.last?.text ?? "") : shownDraft, L("翻译暂不可用"))}return out}@@ -1487,12 +1547,57 @@ final class ListenEngine {for l in lines { onRefined?(l.id, l.text) }}+ /// Stopping: what a sentence cut carried over is a line of its own, not lost with the draft.+ private func flushCarry() {+ guard let c = carry, isRunning else { carry = nil; return }+ carry = nil+ volatileText = ""+ volatileSentence = nil+ sentenceCutHead = nil+ handle(.init(text: c.text, isFinal: true, start: c.start, end: max(c.start, router.fedSeconds()), confidence: nil),+ generation: generation)+ }++ /// Each place the line could end, timed by the first draft that showed it: the words before it+ /// were heard by then. One that moves a character or so as the draft is revised keeps its time.+ private func noteBoundaries(at end: Double) {+ let text = shownDraft+ let carried = text.count - volatileText.count+ let now = HeardText.boundaries(text, language: activeLang?.code ?? "").filter { $0.at > carried }+ seenBoundaries = now.map { b in+ let old = seenBoundaries.first { $0.kind == b.kind && abs($0.at - b.at) <= 1 }+ return (b.at, b.kind, old?.end ?? end)+ }+ }++ /// A clause end for a long line (a Chinese line past 24 characters), or past `capped` any+ /// place between words: the latest one heard a moment ago, with enough before it to be a line.+ private func boundaryCut(_ fed: Double, held: Double) -> (at: Int, kind: HeardText.Boundary, end: Double)? {+ let code = activeLang?.code ?? ""+ let line = HeardText.size(shownDraft)+ let kind: HeardText.Boundary+ if line >= HeardText.capped(code) || held >= 12 { kind = .word }+ else if line >= HeardText.clauseFrom(code) { kind = .clause }+ else { return nil }+ let text = shownDraft+ let fit = seenBoundaries.filter { b in+ b.kind >= kind && b.end > lastCutThrough && b.end > volatileStartClock + 0.5 && fed - b.end >= 0.4+ && HeardText.size(String(text.prefix(b.at))) >= (HeardText.isCJK(text) ? 12 : 5)+ }+ // Past the cap a clause end still beats a word gap, if it leaves at least half the line.+ if kind == .word, let clause = fit.filter({ $0.kind >= .clause && $0.at * 2 >= text.count }).max(by: { $0.at < $1.at }) {+ return clause+ }+ return fit.max { $0.at < $1.at }+ }+/// SpeechTranscriber ends a sentence only at a clear pause; in a quick conversation that can/// take 15–20 s, and the subtitle stays a draft that long (the notes wait for it too). A long- /// line in progress is ended at the next small pause: a dip in the sound, or no new words for- /// a moment.+ /// line in progress is ended where a sentence ends, at the next small pause (a dip in the+ /// sound), at a clause, past a cap between words, or when no new words come for a moment.private func maybeCutSentence() {- guard isRunning, !cutting, let recognizer, !volatileText.isEmpty, volatileText != lastCut else { return }+ guard isRunning, !cutting, let recognizer, !volatileText.isEmpty, volatileText != lastCut,+ (pendingSplit == nil && !cutAsked) || Date().timeIntervalSince(cutAskedAt) > 2 else { return }let cjk = joiner(for: activeLang?.code ?? "") == ""let long = cjk ? volatileText.count >= 24 : volatileText.split(separator: " ").count >= 10guard long else { return }@@ -1502,17 +1607,40 @@ final class ListenEngine {let c = router.clock()let mid = c.pause.end - c.pause.length / 2let through: Double, why: String- if c.silence >= needed {+ var boundary: (at: Int, kind: HeardText.Boundary)?+ // The draft went on past the sentence, and still ends it about there (drafts get revised).+ if let s = volatileSentence, volatileText.count > s.head.count + 1,+ volatileText.prefix(s.head.count + 2).suffix(5).contains(where: { "。!?.!?".contains($0) }), s.end > lastCutThrough,+ s.end > volatileStartClock + 1, c.fed - s.end >= 0.5 {+ // The speaker finished a sentence and went straight on: end the line there. Its "." is+ // the speaker's, so the next piece doesn't join it back (`HeardText.continues`).+ (through, why) = (s.end, "sentence")+ } else if c.silence >= needed {(through, why) = (c.fed, "quiet")} else if c.pause.length >= needed, mid > volatileStartClock + 1.5, mid > lastCutThrough, c.pause.end <= c.fed {(through, why) = (mid, "pause") // a pause already behind us: end the line there+ } else if let b = boundaryCut(c.fed, held: held) {+ (through, why) = (b.end, b.kind == .clause ? "clause" : "word")+ boundary = (b.at, b.kind)} else if Date().timeIntervalSince(volatileChangedAt) >= (held >= 8 ? 0.6 : 1.2) {(through, why) = (c.fed, "stalled")} else {return}cutting = true- cutAsked = true+ cutAskedAt = Date()+ cutAsked = why != "sentence" && boundary == nil+ let carried = shownDraft.count - volatileText.count+ if why == "sentence", let s = volatileSentence {+ sentenceCutHead = s.head+ pendingSplit = (carried + s.head.count, .sentence)+ } else if let b = boundary {+ sentenceCutHead = String(volatileText.prefix(max(0, b.at - carried)))+ pendingSplit = (b.at, b.kind)+ } else {+ sentenceCutHead = nil+ pendingSplit = nil+ }lastCut = volatileTextlastCutThrough = throughlet chars = volatileText.count@@ -1524,14 +1652,16 @@ final class ListenEngine {} catch {debugLog("cut: finalize failed \(error)")self?.cutAsked = false+ self?.sentenceCutHead = nil+ self?.pendingSplit = nil}self?.cutting = false}}private func translateVolatile() {- guard isRunning, !translationOff(), !volatileInFlight, volatileText.count >= 2, volatileText != lastVolatileSent else { return }- let text = volatileText+ let text = shownDraft+ guard isRunning, !translationOff(), !volatileInFlight, text.count >= 2, text != lastVolatileSent else { return }let epoch = volatileEpochlet source = activeLang?.code ?? "auto"lastVolatileSent = textdiff --git a/Tests/CicadaTests/HeardTextTests.swift b/Tests/CicadaTests/HeardTextTests.swiftindex 1e80223..75e0b56 100644--- a/Tests/CicadaTests/HeardTextTests.swift+++ b/Tests/CicadaTests/HeardTextTests.swift@@ -114,4 +114,65 @@ import Testing}print("lines: \(s.lines.count) → \(out.count)")}++ @Test func endsSentenceOnlyAtAFullSentence() {+ #expect(HeardText.endsSentence("いつも動画をご覧いただきありがとうございます。"))+ #expect(HeardText.endsSentence("We should ship the fix this week."))+ #expect(HeardText.endsSentence("Are we shipping it this week?"))+ // Too short to be a line, mid-sentence, trailing off, or a number being read.+ #expect(!HeardText.endsSentence("はい。"))+ #expect(!HeardText.endsSentence("Yes it is."))+ #expect(!HeardText.endsSentence("いつも動画をご覧いただきありがとうござい"))+ #expect(!HeardText.endsSentence("and then we went over the numbers..."))+ #expect(!HeardText.endsSentence("the growth this quarter was about 3."))+ }++ @Test func splitAtSentenceEndKeepsTheRunOnForTheNextLine() {+ // Heard in session 20261108-100300: the cut came back a second into the next sentence.+ let s = HeardText.splitAtSentenceEnd("にもこの新型 iPad mini Proモデルが届いたので開封をしていきたいと思います。前回こちらの動画で")+ #expect(s?.head == "にもこの新型 iPad mini Proモデルが届いたので開封をしていきたいと思います。")+ #expect(s?.tail == "前回こちらの動画で")+ #expect(HeardText.splitAtSentenceEnd("We should ship the fix this week. And then")?.tail == "And then")+ // Nothing after the end, or a head too short to stand alone: left whole.+ #expect(HeardText.splitAtSentenceEnd("開封をしていきたいと思います。今日はですね新型のお話です。") == nil)+ #expect(HeardText.splitAtSentenceEnd("はい。それではですね") == nil)+ }++ @Test func chineseClausesEndAtCommasConnectivesAndParticles() {+ // Heard in a fast review: no 。 for 80 characters.+ let zh = "站着是会弯一点,但是松开它可以恢复原样那真正屁股坐上去的场景实际受力面积会比这个还要大一些所以很多人设想的"+ let clauses = HeardText.boundaries(zh, language: "zh").filter { $0.kind == .clause }.map(\.at)+ #expect(clauses.contains(8)) // after ","+ #expect(clauses.contains(zh.distance(from: zh.startIndex, to: zh.range(of: "所以")!.lowerBound)))+ // "那个" is a word, not the clause word "那"; "吧台" is no particle.+ #expect(!HeardText.boundaries("我们去那个吧台坐一下好不好", language: "zh").contains { $0.kind == .clause })+ #expect(HeardText.boundaries("我们先这样吧然后再说", language: "zh").contains { $0.at == 6 && $0.kind == .clause })+ // Two connectives in a row start one clause, at the first.+ let both = HeardText.boundaries("需求会更小众和纠结一点因为如果你问有些人", language: "zh").filter { $0.kind == .clause }.map(\.at)+ #expect(both == [11])+ #expect(!HeardText.boundaries("还要大一些所以很多人设想的", language: "zh").contains { $0.at == 6 })+ // The final dropped the draft's comma: the word gap there.+ #expect(HeardText.split("要好很多很多即便施加了比较多的下压力而且", near: 6, kind: .clause, language: "zh") == nil)+ #expect(HeardText.split("结论就是他会比要好很多很多即便施加了比较多的下压力", near: 13, kind: .clause, language: "zh")?.tail == "即便施加了比较多的下压力")+ }++ @Test func splitAtClauseNearTheCut() {+ let final = "站着是会弯一点但是松开它可以恢复原样那真正屁股坐上去的场景实际受力面积会比这个还要大一些所以很多人"+ let at = final.distance(from: final.startIndex, to: final.range(of: "所以")!.lowerBound)+ let s = HeardText.split(final, near: at - 2, kind: .clause, language: "zh")+ #expect(s?.tail == "所以很多人")+ // Between words, for a line past the cap: never inside a word.+ let en = "and then we went over all of the numbers for the next quarter with the team in Berlin"+ let w = HeardText.split(en, near: 40, kind: .word, language: "en")+ #expect(w.map { en.hasPrefix($0.head + " ") } == true)+ #expect(w?.head.last?.isLetter == true && w?.tail.first?.isLetter == true)+ // No boundary near the cut: left whole.+ #expect(HeardText.split("站着是会弯一点但是松开它可以恢复原样", near: 3, kind: .clause, language: "zh") == nil)+ }++ @Test func joinsStopAtTheCap() {+ let a = "ではこちらペリペリ剥がしますはいこっちもですねそれではオープンよいしょはいはいで" // 40+ #expect(HeardText.continues(a, "いつもですね", gap: 0.2, cut: true))+ #expect(!HeardText.continues(a, "いつもですねこれですねこちらのフィルムも丁寧に剥がしておお", gap: 0.2, cut: true))+ }}diff --git a/site/changelog.json b/site/changelog.jsonindex d42801a..08b4c0c 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -22,6 +22,14 @@"title": "开会时 Dock 里也有知了。","text": "以前只开着实时纪要时,Ubuntu 的 Dock 里没有知了,只能从顶栏找到它。现在知了开着就在 Dock 里,点图标打开会议记录;关掉会议记录窗口只是把它收进 Dock,不会抢走会议软件的焦点。只想要顶栏的话,在“设置 › 正在听时”里关掉“在 Dock 中显示”。"},+ {+ "kind": "fixed",+ "platforms": [+ "mac"+ ],+ "title": "语速快、不停顿时,实时纪要也一句一行。",+ "text": "以前看语速很快的视频(比如日语、中文 YouTube),说话人几乎不停顿,正在说的那行会一直变长,一段字幕能堆上两三百字。现在一句说完就成一行;中文很少打句号,就在逗号、“所以”“但是”这类词前面断开;实在太长也会在词和词之间断开,不会切断一个词。转写里一段最多两三句。"+ },{"kind": "improved","platforms": [