Repository Public
1// SP Lecture Studio — LectureCore2// File: Packages/LectureCore/Sources/Transcript.swift3// Description: Editable transcript model and caption / chapter writers (SRT, WebVTT, TXT, chapters JSON) on the edited timeline.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct TranscriptSegment: Hashable, Sendable, Codable, Identifiable {10 public var id: UUID11 /// Source timeline range.12 public var range: TimeRange13 public var text: String14 public var confidence: Double?15 /// True once the instructor has edited the text by hand.16 public var edited: Bool17 public init(id: UUID = UUID(), range: TimeRange, text: String, confidence: Double? = nil, edited: Bool = false) {18 self.id = id; self.range = range; self.text = text; self.confidence = confidence; self.edited = edited19 }20}2122public struct Transcript: Hashable, Sendable, Codable {23 public var locale: String24 /// Identifier of the provider that produced it (e.g. "apple.speech.ondevice").25 public var provider: String26 public var createdAt: Date27 public var segments: [TranscriptSegment]28 public init(locale: String, provider: String, createdAt: Date = Date(), segments: [TranscriptSegment]) {29 self.locale = locale; self.provider = provider; self.createdAt = createdAt; self.segments = segments30 }31 public var plainText: String { segments.map(\.text).joined(separator: " ") }32}3334public struct Caption: Hashable, Sendable {35 /// Output timeline range.36 public var range: TimeRange37 public var text: String38}3940public enum CaptionWriter {41 /// Captions on the edited timeline: text inside a cut disappears, text straddling a cut is clipped to what remains.42 /// Long segments are split into readable cues (≤ `maxChars` characters, ≤ `maxDuration` seconds).43 public static func captions(_ transcript: Transcript, map: TimeMap, maxChars: Int = 84, maxDuration: Double = 6) -> [Caption] {44 var out: [Caption] = []45 for seg in transcript.segments.sorted(by: { $0.range.start < $1.range.start }) {46 let text = seg.text.trimmingCharacters(in: .whitespacesAndNewlines)47 guard !text.isEmpty else { continue }48 let pieces = map.outputRanges(for: seg.range)49 let kept = pieces.reduce(MediaTime.zero) { $0 + $1.duration }50 guard let first = pieces.first, let last = pieces.last, kept.ns * 4 >= seg.range.duration.ns else { continue } // mostly cut → dropped51 let range = TimeRange(start: first.start, end: max(last.end, first.start + MediaTime(milliseconds: 300)))52 out.append(contentsOf: split(text: text, range: range, maxChars: maxChars, maxDuration: maxDuration))53 }54 // Cues must not overlap.55 for i in out.indices.dropLast() where out[i].range.end > out[i + 1].range.start {56 out[i].range = TimeRange(start: out[i].range.start, end: max(out[i].range.start, out[i + 1].range.start))57 }58 return out.filter { !$0.range.isEmpty }59 }6061 static func split(text: String, range: TimeRange, maxChars: Int, maxDuration: Double) -> [Caption] {62 let words = text.split(separator: " ").map(String.init)63 let parts = max(1, max(Int((Double(text.count) / Double(maxChars)).rounded(.up)), Int((range.duration.seconds / maxDuration).rounded(.up))))64 guard parts > 1, words.count >= parts else { return [Caption(range: range, text: text)] }65 let total = Double(text.count)66 var out: [Caption] = []67 var cursor = range.start68 var chunk: [String] = []; var consumed = 0.0; var chunkChars = 0.069 let target = total / Double(parts)70 for (i, w) in words.enumerated() {71 chunk.append(w); chunkChars += Double(w.count + 1)72 let isLast = i == words.count - 173 if chunkChars >= target && out.count < parts - 1 || isLast {74 consumed += chunkChars75 let end = isLast ? range.end : range.start + MediaTime(seconds: range.duration.seconds * min(1, consumed / (total + Double(words.count))))76 out.append(Caption(range: TimeRange(start: cursor, end: max(cursor, end)), text: chunk.joined(separator: " ")))77 cursor = end; chunk = []; chunkChars = 078 }79 }80 return out81 }8283 public static func timestamp(_ t: MediaTime, separator: String) -> String {84 let ms = max(0, t.ns) / 1_000_00085 return String(format: "%02d:%02d:%02d%@%03d", ms / 3_600_000, (ms / 60_000) % 60, (ms / 1000) % 60, separator, ms % 1000)86 }8788 public static func srt(_ captions: [Caption]) -> String {89 captions.enumerated().map { i, c in90 "\(i + 1)\n\(timestamp(c.range.start, separator: ",")) --> \(timestamp(c.range.end, separator: ","))\n\(wrap(c.text))\n"91 }.joined(separator: "\n")92 }9394 public static func vtt(_ captions: [Caption]) -> String {95 "WEBVTT\n\n" + captions.map { c in96 "\(timestamp(c.range.start, separator: ".")) --> \(timestamp(c.range.end, separator: "."))\n\(wrap(c.text).replacingOccurrences(of: "-->", with: "→"))\n"97 }.joined(separator: "\n")98 }99100 /// Two balanced lines at most.101 static func wrap(_ text: String, line: Int = 42) -> String {102 guard text.count > line else { return text }103 let words = text.split(separator: " ")104 var best = 0, bestDiff = Int.max, acc = 0105 for (i, w) in words.enumerated().dropLast() {106 acc += w.count + 1107 let diff = abs(acc - (text.count - acc))108 if diff < bestDiff { bestDiff = diff; best = i }109 }110 return words[...best].joined(separator: " ") + "\n" + words[(best + 1)...].joined(separator: " ")111 }112113 public static func plainText(_ transcript: Transcript, map: TimeMap, chapters: [Chapter] = []) -> String {114 var out = ""115 var pending = ChapterGenerator.mapped(chapters, map: map)116 for seg in transcript.segments.sorted(by: { $0.range.start < $1.range.start }) where map.isKept(seg.range.start) || !map.outputRanges(for: seg.range).isEmpty {117 let t = map.toOutput(seg.range.start)118 while let c = pending.first, c.time <= t {119 out += (out.isEmpty ? "" : "\n\n") + "[\(MediaTime.clock(c.time))] \(c.title)\n"; pending.removeFirst()120 }121 out += seg.text.trimmingCharacters(in: .whitespacesAndNewlines) + " "122 }123 return out.trimmingCharacters(in: .whitespacesAndNewlines) + "\n"124 }125126 public struct ChapterFile: Codable, Sendable {127 public struct Entry: Codable, Sendable { public var start: Double; public var timestamp: String; public var title: String }128 public var title: String129 public var duration: Double130 public var chapters: [Entry]131 }132133 public static func chaptersJSON(title: String, chapters: [Chapter], map: TimeMap) throws -> Data {134 let mapped = ChapterGenerator.mapped(chapters, map: map)135 let file = ChapterFile(title: title, duration: map.outputDuration.seconds,136 chapters: mapped.map { .init(start: ($0.time.seconds * 1000).rounded() / 1000, timestamp: MediaTime.clock($0.time), title: $0.title) })137 let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]138 return try enc.encode(file)139 }140141 /// YouTube-style description block ("0:00 Title").142 public static func chapterList(_ chapters: [Chapter], map: TimeMap) -> String {143 ChapterGenerator.mapped(chapters, map: map).map { "\(MediaTime.clock($0.time)) \($0.title)" }.joined(separator: "\n") + "\n"144 }145}146