Branchwell

Jotley / app · jotley.ai / Shared / Services / ServiceConstants.swift

1import Foundation
2
3struct TranscriptUtterance: Codable, Identifiable, Hashable {
4 let id: String
5 var text: String
6 let start: Double?
7 let end: Double?
8 let speaker: Int?
9 let confidence: Double?
10 let isInterim: Bool
11
12 init(
13 id: String = UUID().uuidString,
14 text: String,
15 start: Double? = nil,
16 end: Double? = nil,
17 speaker: Int? = nil,
18 confidence: Double? = nil,
19 isInterim: Bool = false
20 ) {
21 self.id = id
22 self.text = text.trimmingCharacters(in: .whitespacesAndNewlines)
23 self.start = start
24 self.end = end
25 self.speaker = speaker
26 self.confidence = confidence
27 self.isInterim = isInterim
28 }
29
30 var isEmpty: Bool {
31 text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
32 }
33
34 var timestampLabel: String? {
35 guard let start, start.isFinite, start >= 0, start < Double(Int.max) else { return nil }
36 let seconds = Int(start)
37 return String(format: "%02d:%02d", seconds / 60, seconds % 60)
38 }
39
40 static func displayParagraphs(_ utterances: [TranscriptUtterance]) -> [TranscriptUtterance] {
41 utterances.flatMap { coalescedForDisplay([$0]) }
42 }
43
44 static func fallbackUtterances(from transcript: String) -> [TranscriptUtterance] {
45 if transcript.split(whereSeparator: \.isNewline).contains(where: { bracketedTime($0) != nil }) {
46 return parseTranscriptText(transcript)
47 }
48 let paragraphs = transcript
49 .components(separatedBy: .newlines)
50 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
51 .filter { !$0.isEmpty }
52
53 return paragraphs.enumerated().map { TranscriptUtterance(id: "plain-\($0.offset)", text: $0.element) }
54 }
55
56 static func formattedTranscriptText(_ utterances: [Self]) -> String {
57 var text = ""
58 for entry in utterances where !entry.isEmpty {
59 if let timestamp = entry.timestampLabel {
60 if !text.isEmpty { text += "\n" }
61 text += "[\(timestamp)]\n"
62 } else if !text.isEmpty {
63 text += "\n\n"
64 }
65 text += entry.text
66 }
67 return text
68 }
69
70 /// Parse bracketed lines as cue boundaries, retaining the original subsecond
71 /// timing and speaker metadata when an existing timestamp survives an edit.
72 static func parseTranscriptText(_ text: String, preserving original: [Self] = []) -> [Self] {
73 let timed = original.compactMap { entry in
74 entry.start.map { ($0.rounded(.down), entry) }
75 }.filter { $0.1.timestampLabel != nil }
76 var anchors = Dictionary(grouping: timed, by: \.0).mapValues { $0.map(\.1)[...] }
77 var rows: [Self] = []
78 var lines: [Substring] = []
79 var start: Double?
80
81 func flush() {
82 let anchor = start.flatMap { anchors[$0]?.popFirst() }
83 if !lines.isEmpty {
84 let paragraph = lines.joined(separator: "\n")
85 if var entry = anchor {
86 entry.text = paragraph
87 rows.append(entry)
88 } else {
89 rows.append(Self(text: paragraph, start: start))
90 }
91 }
92 lines.removeAll(keepingCapacity: true)
93 start = nil
94 }
95
96 for line in text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {
97 if let time = bracketedTime(line) {
98 flush()
99 start = time
100 } else if line.allSatisfy(\.isWhitespace) {
101 flush()
102 } else {
103 lines.append(line)
104 }
105 }
106 flush()
107 return rows
108 }
109
110 private static func bracketedTime(_ line: Substring) -> Double? {
111 guard line.first == "[", line.last == "]" else { return nil }
112 let parts = line.dropFirst().dropLast().split(separator: ":", omittingEmptySubsequences: false)
113 guard parts.count == 2, parts[0].count >= 2, parts[1].count == 2,
114 parts.allSatisfy({ $0.utf8.allSatisfy { (48...57).contains($0) } }),
115 let minutes = Int(parts[0]), let seconds = Int(parts[1]), seconds < 60,
116 minutes <= (Int.max - 59) / 60 else { return nil }
117 return Double(minutes * 60 + seconds)
118 }
119
120 static func deduplicated(_ utterances: [TranscriptUtterance]) -> [TranscriptUtterance] {
121 var results: [TranscriptUtterance] = []
122 var needsSorting = false
123 var lastStartTime: Double?
124
125 for rawUtterance in utterances {
126 let utterance = TranscriptUtterance(
127 id: rawUtterance.id,
128 text: rawUtterance.text,
129 start: rawUtterance.start,
130 end: rawUtterance.end,
131 speaker: rawUtterance.speaker,
132 confidence: rawUtterance.confidence,
133 isInterim: rawUtterance.isInterim
134 )
135
136 guard !utterance.isEmpty else { continue }
137
138 if let last = results.last, last.isLikelyDuplicate(of: utterance) {
139 continue
140 }
141
142 if let start = utterance.start {
143 if let lastStartTime, start + 0.0001 < lastStartTime {
144 needsSorting = true
145 }
146 lastStartTime = start
147 }
148
149 results.append(utterance)
150 }
151
152 guard needsSorting else { return results }
153
154 // Keep deterministic ordering while preferring timestamp order when available.
155 return results
156 .enumerated()
157 .sorted { lhs, rhs in
158 let left = lhs.element
159 let right = rhs.element
160
161 switch (left.start, right.start) {
162 case let (l?, r?) where abs(l - r) > 0.0001:
163 return l < r
164 default:
165 return lhs.offset < rhs.offset
166 }
167 }
168 .map(\.element)
169 }
170
171 /// Coalesces short utterances into larger timestamped chunks for easier reading.
172 /// This keeps timing metadata while avoiding overly fragmented, word-level bubbles.
173 static func coalescedForDisplay(
174 _ utterances: [TranscriptUtterance],
175 minWordsPerChunk: Int = 8,
176 maxWordsPerChunk: Int = 20,
177 maxDurationSeconds: Double = 12,
178 maxSentencesPerChunk: Int = 2,
179 pauseSeconds: Double = 2
180 ) -> [TranscriptUtterance] {
181 let cleaned = deduplicated(utterances)
182 .filter { !$0.isInterim && !$0.isEmpty }
183
184 var coalesced: [TranscriptUtterance] = []
185 var buffer: [TranscriptUtterance] = []
186 var bufferedWordCount = 0
187 var bufferedSentenceCount = 0
188
189 func flush() {
190 guard let first = buffer.first else { return }
191 coalesced.append(buffer.count == 1 ? first : mergeUtterancesForDisplay(buffer))
192 buffer.removeAll(keepingCapacity: true)
193 bufferedWordCount = 0
194 bufferedSentenceCount = 0
195 }
196
197 for utterance in cleaned {
198 let chunks = splitOversizedUtterance(utterance, maxWordsPerChunk: maxWordsPerChunk,
199 maxSentencesPerChunk: maxSentencesPerChunk, maxDurationSeconds: maxDurationSeconds)
200 // Already split paragraphs and legacy lines are standalone.
201 guard chunks.count == 1, let start = utterance.start else {
202 flush()
203 coalesced.append(contentsOf: chunks)
204 continue
205 }
206
207 let incomingWordCount = wordCount(in: utterance.text)
208 let sentenceBoundary = endsSentence(utterance.text)
209 if let previous = buffer.last {
210 let pause = previous.end.map { start - $0 } ?? 0
211 if pause >= pauseSeconds || didSpeakerChange(current: buffer, incoming: utterance)
212 || bufferedWordCount + incomingWordCount > maxWordsPerChunk {
213 flush()
214 }
215 }
216 buffer.append(utterance)
217 bufferedWordCount += incomingWordCount
218 if sentenceBoundary {
219 bufferedSentenceCount += 1
220 }
221
222 let duration = mergedDuration(of: buffer)
223
224 if bufferedWordCount >= maxWordsPerChunk ||
225 duration >= maxDurationSeconds ||
226 (bufferedSentenceCount >= maxSentencesPerChunk && bufferedWordCount >= minWordsPerChunk) ||
227 (bufferedWordCount >= minWordsPerChunk && sentenceBoundary) {
228 flush()
229 }
230 }
231
232 flush()
233
234 return coalesced
235 }
236
237 private static func splitOversizedUtterance(
238 _ utterance: TranscriptUtterance,
239 maxWordsPerChunk: Int,
240 maxSentencesPerChunk: Int,
241 maxDurationSeconds: Double
242 ) -> [TranscriptUtterance] {
243 let paragraphs = utterance.text.components(separatedBy: .newlines)
244 .map { $0.trimmingCharacters(in: .whitespaces) }
245 .filter { !$0.isEmpty }
246 let sentenceParts = paragraphs.map { sentenceUnits(from: $0) }
247 let totalWords = wordCount(in: utterance.text)
248 let totalSentences = sentenceParts.reduce(0) { $0 + $1.count }
249 let utteranceDuration = mergedDuration(of: [utterance])
250
251 let shouldSplit = paragraphs.count > 1 || totalWords > maxWordsPerChunk ||
252 totalSentences > maxSentencesPerChunk ||
253 utteranceDuration > maxDurationSeconds * 1.15
254
255 guard shouldSplit else { return [utterance] }
256
257 var chunkTexts: [String] = []
258 var chunkWordCounts: [Int] = []
259 var buffer: [String] = []
260 var bufferedWords = 0
261 var bufferedSentences = 0
262
263 func flushBuffer() {
264 guard !buffer.isEmpty else { return }
265
266 let chunkText = buffer.joined(separator: " ")
267 .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
268 .trimmingCharacters(in: .whitespacesAndNewlines)
269
270 guard !chunkText.isEmpty else {
271 buffer.removeAll(keepingCapacity: true)
272 bufferedWords = 0
273 bufferedSentences = 0
274 return
275 }
276
277 chunkTexts.append(chunkText)
278 chunkWordCounts.append(max(wordCount(in: chunkText), 1))
279 buffer.removeAll(keepingCapacity: true)
280 bufferedWords = 0
281 bufferedSentences = 0
282 }
283
284 for paragraph in sentenceParts {
285 let units = paragraph.flatMap { part in
286 wordCount(in: part) <= maxWordsPerChunk ? [part] : splitByWordCount(part, maxWords: maxWordsPerChunk)
287 }
288 for unit in units {
289 let unitWordCount = wordCount(in: unit)
290 if bufferedWords + unitWordCount > maxWordsPerChunk { flushBuffer() }
291 buffer.append(unit)
292 bufferedWords += unitWordCount
293 bufferedSentences += 1
294
295 if bufferedWords >= maxWordsPerChunk || bufferedSentences >= maxSentencesPerChunk {
296 flushBuffer()
297 }
298 }
299 flushBuffer()
300 }
301
302 guard chunkTexts.count > 1 else { return [utterance] }
303
304 let timeBounds = interpolatedTimeBounds(for: utterance)
305
306 let totalWordWeight = max(chunkWordCounts.reduce(0, +), 1)
307 var currentStart = timeBounds?.start ?? 0
308 var splitChunks: [TranscriptUtterance] = []
309 splitChunks.reserveCapacity(chunkTexts.count)
310
311 for index in chunkTexts.indices {
312 let chunkText = chunkTexts[index]
313 let chunkWeight = Double(chunkWordCounts[index]) / Double(totalWordWeight)
314
315 let chunkStart: Double?
316 let chunkEnd: Double?
317 if let timeBounds {
318 chunkStart = currentStart
319 if index == chunkTexts.count - 1 {
320 chunkEnd = timeBounds.end
321 } else {
322 let estimatedDuration = timeBounds.duration * chunkWeight
323 chunkEnd = min(timeBounds.end, currentStart + estimatedDuration)
324 }
325 currentStart = chunkEnd ?? currentStart
326 } else {
327 chunkStart = index == chunkTexts.startIndex ? utterance.start : nil
328 chunkEnd = index == chunkTexts.indices.last ? utterance.end : nil
329 }
330
331 splitChunks.append(
332 TranscriptUtterance(
333 id: "\(utterance.id)-\(index)",
334 text: chunkText,
335 start: chunkStart,
336 end: chunkEnd,
337 speaker: utterance.speaker,
338 confidence: utterance.confidence,
339 isInterim: false
340 )
341 )
342 }
343
344 return splitChunks
345 }
346
347 private static func sentenceUnits(from text: String) -> [String] {
348 let normalized = text
349 .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
350 .trimmingCharacters(in: .whitespacesAndNewlines)
351
352 guard !normalized.isEmpty else { return [] }
353
354 let segmented = normalized.replacingOccurrences(
355 of: "(?<=[.!?])\\s+",
356 with: "\n",
357 options: .regularExpression
358 )
359
360 let units = segmented
361 .components(separatedBy: "\n")
362 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
363 .filter { !$0.isEmpty }
364
365 return units.isEmpty ? [normalized] : units
366 }
367
368 private static func splitByWordCount(_ text: String, maxWords: Int) -> [String] {
369 let words = text.split(whereSeparator: \.isWhitespace)
370 guard !words.isEmpty else { return [] }
371
372 var chunks: [String] = []
373 chunks.reserveCapacity(max(1, Int(ceil(Double(words.count) / Double(max(maxWords, 1))))))
374
375 var startIndex = 0
376 while startIndex < words.count {
377 let endIndex = min(startIndex + max(maxWords, 1), words.count)
378 let chunk = words[startIndex..<endIndex].map(String.init).joined(separator: " ")
379 chunks.append(chunk)
380 startIndex = endIndex
381 }
382
383 return chunks
384 }
385
386 private static func interpolatedTimeBounds(for utterance: TranscriptUtterance) -> (start: Double, end: Double, duration: Double)? {
387 if let start = utterance.start,
388 let end = utterance.end,
389 start.isFinite, end.isFinite, start >= 0, end > start {
390 return (start: start, end: end, duration: end - start)
391 }
392 return nil
393 }
394
395 private func isLikelyDuplicate(of other: TranscriptUtterance) -> Bool {
396 guard normalized(text) == normalized(other.text) else { return false }
397
398 switch (start, other.start, end, other.end) {
399 case let (a?, b?, c?, d?):
400 return abs(a - b) <= 0.25 && abs(c - d) <= 0.25
401 case let (a?, b?, _, _):
402 return abs(a - b) <= 0.25
403 case let (_, _, c?, d?):
404 return abs(c - d) <= 0.25
405 default:
406 return false
407 }
408 }
409
410 private func normalized(_ value: String) -> String {
411 value
412 .trimmingCharacters(in: .whitespacesAndNewlines)
413 .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
414 .lowercased()
415 }
416
417 private static func mergeUtterancesForDisplay(_ utterances: [TranscriptUtterance]) -> TranscriptUtterance {
418 let mergedText = utterances
419 .map { $0.text.trimmingCharacters(in: .whitespacesAndNewlines) }
420 .filter { !$0.isEmpty }
421 .joined(separator: " ")
422 .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
423 .trimmingCharacters(in: .whitespacesAndNewlines)
424
425 let starts = utterances.compactMap(\.start)
426 let ends = utterances.compactMap(\.end)
427 let confidences = utterances.compactMap(\.confidence)
428 let dominantSpeaker = utterances
429 .compactMap(\.speaker)
430 .reduce(into: [Int: Int]()) { counts, speaker in
431 counts[speaker, default: 0] += 1
432 }
433 .max(by: { $0.value < $1.value })?
434 .key
435
436 return TranscriptUtterance(
437 id: utterances.first?.id ?? UUID().uuidString,
438 text: mergedText,
439 start: starts.isEmpty ? nil : starts.min(),
440 end: ends.isEmpty ? nil : ends.max(),
441 speaker: dominantSpeaker,
442 confidence: confidences.isEmpty ? nil : confidences.reduce(0, +) / Double(confidences.count),
443 isInterim: false
444 )
445 }
446
447 private static func mergedDuration(of utterances: [TranscriptUtterance]) -> Double {
448 guard let start = utterances.compactMap(\.start).min(),
449 let end = utterances.compactMap(\.end).max() else {
450 return 0
451 }
452 return max(0, end - start)
453 }
454
455 private static func didSpeakerChange(current: [TranscriptUtterance], incoming: TranscriptUtterance) -> Bool {
456 guard let incomingSpeaker = incoming.speaker else { return false }
457 guard let currentSpeaker = current.compactMap(\.speaker).last else { return false }
458 return currentSpeaker != incomingSpeaker
459 }
460
461 private static func endsSentence(_ text: String) -> Bool {
462 guard let lastCharacter = text.trimmingCharacters(in: .whitespacesAndNewlines).last else {
463 return false
464 }
465 return lastCharacter == "." || lastCharacter == "!" || lastCharacter == "?"
466 }
467
468 private static func wordCount(in text: String) -> Int {
469 text.split(whereSeparator: \.isWhitespace).count
470 }
471}
472
473/// A text correction keeps each segment's recorded timing and speaker metadata.
474/// Timing is never invented for imported or older plain-text transcripts.
475struct TranscriptEditDraft: Equatable {
476 let originalText: String
477 let originalUtterances: [TranscriptUtterance]
478 private let initialSegments: [TranscriptUtterance]
479 private let initialEditorText: String
480 private var editedText: String?
481 var segments: [TranscriptUtterance]
482
483 init(text: String, utterances: [TranscriptUtterance], editorText: String? = nil) {
484 originalText = text
485 originalUtterances = utterances
486 let paragraphs: [TranscriptUtterance]
487 if utterances.isEmpty {
488 let fallback = TranscriptUtterance.fallbackUtterances(from: text)
489 paragraphs = fallback.contains { $0.timestampLabel != nil }
490 ? fallback
491 : TranscriptUtterance.coalescedForDisplay(fallback)
492 } else {
493 paragraphs = utterances
494 }
495 segments = paragraphs.isEmpty ? [TranscriptUtterance(id: "empty", text: "")] : paragraphs
496 initialSegments = segments
497 initialEditorText = editorText ?? (paragraphs.contains { $0.timestampLabel != nil }
498 ? TranscriptUtterance.formattedTranscriptText(paragraphs)
499 : text)
500 }
501
502 var editorText: String {
503 get {
504 editedText ?? (segments == initialSegments ? initialEditorText : TranscriptUtterance.formattedTranscriptText(segments))
505 }
506 set {
507 editedText = newValue
508 segments = TranscriptUtterance.parseTranscriptText(newValue, preserving: initialSegments)
509 }
510 }
511 var hasChanges: Bool { editorText != initialEditorText }
512 var hasTimestamps: Bool { segments.contains { $0.timestampLabel != nil } }
513 var text: String {
514 if !hasTimestamps, let editedText { return editedText }
515 return savedUtterances.map(\.text).joined(separator: "\n\n")
516 }
517 func matchCount(for query: TranscriptFindQuery) -> Int {
518 if !hasTimestamps {
519 return query.matchCount(in: editorText)
520 }
521 guard let pattern = query.pattern else { return 0 }
522 return segments.reduce(0) { $0 + pattern.numberOfMatches(in: $1.text, range: NSRange($1.text.startIndex..., in: $1.text)) }
523 }
524
525 mutating func replaceAll(_ query: TranscriptFindQuery, with replacement: String) {
526 if !hasTimestamps {
527 editorText = query.replacingMatches(in: editorText, with: replacement)
528 return
529 }
530 guard let pattern = query.pattern else { return }
531 let literal = NSRegularExpression.escapedTemplate(for: replacement)
532 for index in segments.indices {
533 let text = segments[index].text
534 segments[index].text = pattern.stringByReplacingMatches(in: text,
535 range: NSRange(text.startIndex..., in: text), withTemplate: literal)
536 }
537 editedText = TranscriptUtterance.formattedTranscriptText(segments)
538 }
539 var savedUtterances: [TranscriptUtterance] {
540 segments.filter { !$0.isEmpty }.map {
541 TranscriptUtterance(id: $0.id, text: $0.text, start: $0.start, end: $0.end,
542 speaker: $0.speaker, confidence: $0.confidence, isInterim: false)
543 }
544 }
545}
546
547struct TranscriptFindQuery {
548 var text = ""
549 var matchCase = false
550 var wholeWords = true
551
552 func matchCount(in text: String) -> Int {
553 pattern?.numberOfMatches(in: text, range: NSRange(text.startIndex..., in: text)) ?? 0
554 }
555
556 func replacingMatches(in text: String, with replacement: String) -> String {
557 pattern?.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text),
558 withTemplate: NSRegularExpression.escapedTemplate(for: replacement)) ?? text
559 }
560
561 var pattern: NSRegularExpression? {
562 guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
563 let escaped = NSRegularExpression.escapedPattern(for: text)
564 let wordCharacter = #"[\p{L}\p{M}\p{N}_]"#
565 let pattern = wholeWords ? "(?<!\(wordCharacter))\(escaped)(?!\(wordCharacter))" : escaped
566 return try? NSRegularExpression(pattern: pattern, options: matchCase ? [] : .caseInsensitive)
567 }
568}
569
570// MARK: - Common Response Structures
571
572struct Template: Codable {
573 let key: String
574 let title: String
575 let description: String
576 let category: String?
577}