|
| 1 | +@preconcurrency import CoreML |
| 2 | +import Foundation |
| 3 | + |
| 4 | +/// Manager for Parakeet CTC zh-CN transcription |
| 5 | +/// |
| 6 | +/// This manager handles the full pipeline for Mandarin Chinese CTC transcription: |
| 7 | +/// 1. Preprocessor: Audio → Mel spectrogram |
| 8 | +/// 2. Encoder: Mel → Encoder features |
| 9 | +/// 3. CTC Decoder: Encoder features → CTC logits |
| 10 | +/// 4. Greedy CTC decoding: Logits → Text |
| 11 | +public actor CtcZhCnManager { |
| 12 | + |
| 13 | + private let models: CtcZhCnModels |
| 14 | + private let maxAudioSamples: Int |
| 15 | + private let sampleRate: Int |
| 16 | + |
| 17 | + private static let logger = AppLogger(category: "CtcZhCnManager") |
| 18 | + |
| 19 | + /// Initialize with pre-loaded models |
| 20 | + public init(models: CtcZhCnModels, maxAudioSamples: Int = 240_000, sampleRate: Int = 16_000) { |
| 21 | + self.models = models |
| 22 | + self.maxAudioSamples = maxAudioSamples |
| 23 | + self.sampleRate = sampleRate |
| 24 | + } |
| 25 | + |
| 26 | + /// Convenience initializer that loads models from default cache directory |
| 27 | + public static func load( |
| 28 | + useInt8Encoder: Bool = true, |
| 29 | + configuration: MLModelConfiguration? = nil, |
| 30 | + progressHandler: DownloadUtils.ProgressHandler? = nil |
| 31 | + ) async throws -> CtcZhCnManager { |
| 32 | + let models = try await CtcZhCnModels.downloadAndLoad( |
| 33 | + useInt8Encoder: useInt8Encoder, |
| 34 | + configuration: configuration, |
| 35 | + progressHandler: progressHandler |
| 36 | + ) |
| 37 | + return CtcZhCnManager(models: models) |
| 38 | + } |
| 39 | + |
| 40 | + /// Transcribe audio to text using CTC decoding |
| 41 | + /// |
| 42 | + /// - Parameters: |
| 43 | + /// - audio: Audio samples (mono, 16kHz) |
| 44 | + /// - audioLength: Optional audio length (if nil, uses audio.count) |
| 45 | + /// - Returns: Transcribed text |
| 46 | + public func transcribe( |
| 47 | + audio: [Float], |
| 48 | + audioLength: Int? = nil |
| 49 | + ) throws -> String { |
| 50 | + let actualLength = audioLength ?? audio.count |
| 51 | + |
| 52 | + // Pad or truncate audio to maxAudioSamples |
| 53 | + let paddedAudio = padOrTruncateAudio(audio, targetLength: maxAudioSamples) |
| 54 | + |
| 55 | + // Step 1: Preprocessor (audio → mel spectrogram) |
| 56 | + let melOutput = try runPreprocessor(audio: paddedAudio, audioLength: actualLength) |
| 57 | + |
| 58 | + // Step 2: Encoder (mel → encoder features) |
| 59 | + let encoderOutput = try runEncoder(mel: melOutput.mel, melLength: melOutput.melLength) |
| 60 | + |
| 61 | + // Step 3: CTC Decoder (encoder features → CTC logits) |
| 62 | + let ctcLogits = try runCtcDecoder(encoderOutput: encoderOutput) |
| 63 | + |
| 64 | + // Step 4: CTC decoding (logits → text) |
| 65 | + let text = greedyCtcDecode(logits: ctcLogits) |
| 66 | + |
| 67 | + return text |
| 68 | + } |
| 69 | + |
| 70 | + /// Transcribe audio file to text |
| 71 | + /// |
| 72 | + /// - Parameters: |
| 73 | + /// - audioURL: URL to audio file (will be resampled to 16kHz mono) |
| 74 | + /// - Returns: Transcribed text |
| 75 | + public func transcribe(audioURL: URL) throws -> String { |
| 76 | + // Load and convert audio |
| 77 | + let converter = AudioConverter(sampleRate: Double(sampleRate)) |
| 78 | + let samples = try converter.resampleAudioFile(audioURL) |
| 79 | + |
| 80 | + return try transcribe(audio: samples) |
| 81 | + } |
| 82 | + |
| 83 | + // MARK: - Private Pipeline Methods |
| 84 | + |
| 85 | + private struct MelOutput { |
| 86 | + let mel: MLMultiArray |
| 87 | + let melLength: MLMultiArray |
| 88 | + } |
| 89 | + |
| 90 | + private func runPreprocessor(audio: [Float], audioLength: Int) throws -> MelOutput { |
| 91 | + // Create input arrays |
| 92 | + let audioArray = try MLMultiArray(shape: [1, maxAudioSamples as NSNumber], dataType: .float32) |
| 93 | + for (i, sample) in audio.enumerated() where i < maxAudioSamples { |
| 94 | + audioArray[i] = NSNumber(value: sample) |
| 95 | + } |
| 96 | + |
| 97 | + let audioLengthArray = try MLMultiArray(shape: [1], dataType: .int32) |
| 98 | + audioLengthArray[0] = NSNumber(value: min(audioLength, maxAudioSamples)) |
| 99 | + |
| 100 | + // Run preprocessor |
| 101 | + let input = try MLDictionaryFeatureProvider( |
| 102 | + dictionary: [ |
| 103 | + "audio_signal": MLFeatureValue(multiArray: audioArray), |
| 104 | + "audio_length": MLFeatureValue(multiArray: audioLengthArray), |
| 105 | + ] |
| 106 | + ) |
| 107 | + let output = try models.preprocessor.prediction(from: input) |
| 108 | + |
| 109 | + guard |
| 110 | + let mel = output.featureValue(for: "mel")?.multiArrayValue, |
| 111 | + let melLength = output.featureValue(for: "mel_length")?.multiArrayValue |
| 112 | + else { |
| 113 | + throw ASRError.processingFailed("Failed to extract mel or mel_length from preprocessor output") |
| 114 | + } |
| 115 | + |
| 116 | + return MelOutput(mel: mel, melLength: melLength) |
| 117 | + } |
| 118 | + |
| 119 | + private func runEncoder(mel: MLMultiArray, melLength: MLMultiArray) throws -> MLMultiArray { |
| 120 | + // Run encoder |
| 121 | + let input = try MLDictionaryFeatureProvider( |
| 122 | + dictionary: [ |
| 123 | + "audio_signal": MLFeatureValue(multiArray: mel), |
| 124 | + "length": MLFeatureValue(multiArray: melLength), |
| 125 | + ] |
| 126 | + ) |
| 127 | + let output = try models.encoder.prediction(from: input) |
| 128 | + |
| 129 | + guard let encoderOutput = output.featureValue(for: "encoder_output")?.multiArrayValue else { |
| 130 | + throw ASRError.processingFailed("Failed to extract encoder_output from encoder") |
| 131 | + } |
| 132 | + |
| 133 | + return encoderOutput |
| 134 | + } |
| 135 | + |
| 136 | + private func runCtcDecoder(encoderOutput: MLMultiArray) throws -> MLMultiArray { |
| 137 | + // Run CTC decoder head |
| 138 | + let input = try MLDictionaryFeatureProvider( |
| 139 | + dictionary: [ |
| 140 | + "encoder_output": MLFeatureValue(multiArray: encoderOutput) |
| 141 | + ] |
| 142 | + ) |
| 143 | + let output = try models.decoder.prediction(from: input) |
| 144 | + |
| 145 | + guard let ctcLogits = output.featureValue(for: "ctc_logits")?.multiArrayValue else { |
| 146 | + throw ASRError.processingFailed("Failed to extract ctc_logits from decoder") |
| 147 | + } |
| 148 | + |
| 149 | + return ctcLogits |
| 150 | + } |
| 151 | + |
| 152 | + private func greedyCtcDecode(logits: MLMultiArray) -> String { |
| 153 | + // logits shape: [1, T, vocab_size+1] where T is time steps (188) |
| 154 | + // vocab_size = 7000, blank_id = 7000 |
| 155 | + |
| 156 | + let timeSteps = logits.shape[1].intValue |
| 157 | + let vocabSize = logits.shape[2].intValue |
| 158 | + |
| 159 | + var decoded: [Int] = [] |
| 160 | + var prevLabel: Int? = nil |
| 161 | + |
| 162 | + for t in 0..<timeSteps { |
| 163 | + // Find argmax at this time step |
| 164 | + var maxLogit: Float = -.infinity |
| 165 | + var maxLabel = 0 |
| 166 | + |
| 167 | + for v in 0..<vocabSize { |
| 168 | + let logit = logits[[0, t as NSNumber, v as NSNumber]].floatValue |
| 169 | + if logit > maxLogit { |
| 170 | + maxLogit = logit |
| 171 | + maxLabel = v |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + // CTC collapse: skip blanks and repeats |
| 176 | + if maxLabel != models.blankId && maxLabel != prevLabel { |
| 177 | + decoded.append(maxLabel) |
| 178 | + } |
| 179 | + prevLabel = maxLabel |
| 180 | + } |
| 181 | + |
| 182 | + // Convert token IDs to text |
| 183 | + var text = "" |
| 184 | + for tokenId in decoded { |
| 185 | + if let token = models.vocabulary[tokenId] { |
| 186 | + text += token |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + // Replace SentencePiece underscores with spaces |
| 191 | + text = text.replacingOccurrences(of: "▁", with: " ") |
| 192 | + |
| 193 | + return text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 194 | + } |
| 195 | + |
| 196 | + private func padOrTruncateAudio(_ audio: [Float], targetLength: Int) -> [Float] { |
| 197 | + var result = audio |
| 198 | + if result.count < targetLength { |
| 199 | + // Pad with zeros |
| 200 | + result.append(contentsOf: Array(repeating: 0.0, count: targetLength - result.count)) |
| 201 | + } else if result.count > targetLength { |
| 202 | + // Truncate |
| 203 | + result = Array(result.prefix(targetLength)) |
| 204 | + } |
| 205 | + return result |
| 206 | + } |
| 207 | +} |
0 commit comments