-
Notifications
You must be signed in to change notification settings - Fork 422
Add experimental CTC zh-CN Mandarin ASR #476
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Alex-Wengg
merged 18 commits into
main
from
fix/swift6-concurrency-slidingwindow-rebased
Apr 3, 2026
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
ab91ac7
Fix Swift 6 concurrency errors in SlidingWindowAsrManager
Alex-Wengg 0e0e1df
Fix partial state mutation in processWindow
Alex-Wengg 9cea6a0
Add CTC zh-CN Mandarin Chinese ASR integration
Alex-Wengg 9890138
Add CTC zh-CN THCHS-30 benchmark pipeline
Alex-Wengg 82a3a09
Fix non-exhaustive switch: Add .ctcZhCn case to AsrManager decoder se…
Alex-Wengg 8c653a9
Add CTC zh-CN THCHS-30 benchmark results to documentation
Alex-Wengg 33c80f8
Fix CTC zh-CN benchmark results: full 2,495-sample THCHS-30 run
Alex-Wengg 415233a
Remove CTC_ZH_CN_BENCHMARK.md
Alex-Wengg ecf3c84
Update CTC zh-CN benchmark docs to focus on full THCHS-30 dataset
Alex-Wengg ace47fa
Address Devin review findings for CTC zh-CN
Alex-Wengg 976022d
Mark CTC zh-CN as experimental feature
Alex-Wengg d8e564b
Fix compilation error: Use Unicode escapes for Chinese curly quotes
Alex-Wengg 943a3c5
Address 2 new Devin review findings
Alex-Wengg dfe4237
Fix compilation error in CtcZhCnTests: Use Unicode escapes for curly …
Alex-Wengg 55e0561
Remove CTC zh-CN CI workflow (experimental feature)
Alex-Wengg 69b21cb
Address 2 more Devin review findings for CTC zh-CN
Alex-Wengg 95ec104
Remove Python validation scripts for CTC zh-CN (experimental feature)
Alex-Wengg 9dc0a03
Fix fatal error in levenshteinDistance with empty arrays
Alex-Wengg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,207 @@ | ||
| @preconcurrency import CoreML | ||
| import Foundation | ||
|
|
||
| /// Manager for Parakeet CTC zh-CN transcription | ||
| /// | ||
| /// This manager handles the full pipeline for Mandarin Chinese CTC transcription: | ||
| /// 1. Preprocessor: Audio → Mel spectrogram | ||
| /// 2. Encoder: Mel → Encoder features | ||
| /// 3. CTC Decoder: Encoder features → CTC logits | ||
| /// 4. Greedy CTC decoding: Logits → Text | ||
| public actor CtcZhCnManager { | ||
|
|
||
| private let models: CtcZhCnModels | ||
| private let maxAudioSamples: Int | ||
| private let sampleRate: Int | ||
|
|
||
| private static let logger = AppLogger(category: "CtcZhCnManager") | ||
|
|
||
| /// Initialize with pre-loaded models | ||
| public init(models: CtcZhCnModels, maxAudioSamples: Int = 240_000, sampleRate: Int = 16_000) { | ||
| self.models = models | ||
| self.maxAudioSamples = maxAudioSamples | ||
| self.sampleRate = sampleRate | ||
| } | ||
|
|
||
| /// Convenience initializer that loads models from default cache directory | ||
| public static func load( | ||
| useInt8Encoder: Bool = true, | ||
| configuration: MLModelConfiguration? = nil, | ||
| progressHandler: DownloadUtils.ProgressHandler? = nil | ||
| ) async throws -> CtcZhCnManager { | ||
| let models = try await CtcZhCnModels.downloadAndLoad( | ||
| useInt8Encoder: useInt8Encoder, | ||
| configuration: configuration, | ||
| progressHandler: progressHandler | ||
| ) | ||
| return CtcZhCnManager(models: models) | ||
| } | ||
|
|
||
| /// Transcribe audio to text using CTC decoding | ||
| /// | ||
| /// - Parameters: | ||
| /// - audio: Audio samples (mono, 16kHz) | ||
| /// - audioLength: Optional audio length (if nil, uses audio.count) | ||
| /// - Returns: Transcribed text | ||
| public func transcribe( | ||
| audio: [Float], | ||
| audioLength: Int? = nil | ||
| ) throws -> String { | ||
| let actualLength = audioLength ?? audio.count | ||
|
|
||
| // Pad or truncate audio to maxAudioSamples | ||
| let paddedAudio = padOrTruncateAudio(audio, targetLength: maxAudioSamples) | ||
|
|
||
| // Step 1: Preprocessor (audio → mel spectrogram) | ||
| let melOutput = try runPreprocessor(audio: paddedAudio, audioLength: actualLength) | ||
|
|
||
| // Step 2: Encoder (mel → encoder features) | ||
| let encoderOutput = try runEncoder(mel: melOutput.mel, melLength: melOutput.melLength) | ||
|
|
||
| // Step 3: CTC Decoder (encoder features → CTC logits) | ||
| let ctcLogits = try runCtcDecoder(encoderOutput: encoderOutput) | ||
|
|
||
| // Step 4: CTC decoding (logits → text) | ||
| let text = greedyCtcDecode(logits: ctcLogits) | ||
|
|
||
| return text | ||
| } | ||
|
|
||
| /// Transcribe audio file to text | ||
| /// | ||
| /// - Parameters: | ||
| /// - audioURL: URL to audio file (will be resampled to 16kHz mono) | ||
| /// - Returns: Transcribed text | ||
| public func transcribe(audioURL: URL) throws -> String { | ||
| // Load and convert audio | ||
| let converter = AudioConverter(sampleRate: Double(sampleRate)) | ||
| let samples = try converter.resampleAudioFile(audioURL) | ||
|
|
||
| return try transcribe(audio: samples) | ||
| } | ||
|
|
||
| // MARK: - Private Pipeline Methods | ||
|
|
||
| private struct MelOutput { | ||
| let mel: MLMultiArray | ||
| let melLength: MLMultiArray | ||
| } | ||
|
|
||
| private func runPreprocessor(audio: [Float], audioLength: Int) throws -> MelOutput { | ||
| // Create input arrays | ||
| let audioArray = try MLMultiArray(shape: [1, maxAudioSamples as NSNumber], dataType: .float32) | ||
| for (i, sample) in audio.enumerated() where i < maxAudioSamples { | ||
| audioArray[i] = NSNumber(value: sample) | ||
| } | ||
|
|
||
| let audioLengthArray = try MLMultiArray(shape: [1], dataType: .int32) | ||
| audioLengthArray[0] = NSNumber(value: min(audioLength, maxAudioSamples)) | ||
|
|
||
| // Run preprocessor | ||
| let input = try MLDictionaryFeatureProvider( | ||
| dictionary: [ | ||
| "audio_signal": MLFeatureValue(multiArray: audioArray), | ||
| "audio_length": MLFeatureValue(multiArray: audioLengthArray), | ||
| ] | ||
| ) | ||
| let output = try models.preprocessor.prediction(from: input) | ||
|
|
||
| guard | ||
| let mel = output.featureValue(for: "mel")?.multiArrayValue, | ||
| let melLength = output.featureValue(for: "mel_length")?.multiArrayValue | ||
| else { | ||
| throw ASRError.processingFailed("Failed to extract mel or mel_length from preprocessor output") | ||
| } | ||
|
|
||
| return MelOutput(mel: mel, melLength: melLength) | ||
| } | ||
|
|
||
| private func runEncoder(mel: MLMultiArray, melLength: MLMultiArray) throws -> MLMultiArray { | ||
| // Run encoder | ||
| let input = try MLDictionaryFeatureProvider( | ||
| dictionary: [ | ||
| "audio_signal": MLFeatureValue(multiArray: mel), | ||
| "length": MLFeatureValue(multiArray: melLength), | ||
| ] | ||
| ) | ||
| let output = try models.encoder.prediction(from: input) | ||
|
|
||
| guard let encoderOutput = output.featureValue(for: "encoder_output")?.multiArrayValue else { | ||
| throw ASRError.processingFailed("Failed to extract encoder_output from encoder") | ||
| } | ||
|
|
||
| return encoderOutput | ||
| } | ||
|
|
||
| private func runCtcDecoder(encoderOutput: MLMultiArray) throws -> MLMultiArray { | ||
| // Run CTC decoder head | ||
| let input = try MLDictionaryFeatureProvider( | ||
| dictionary: [ | ||
| "encoder_output": MLFeatureValue(multiArray: encoderOutput) | ||
| ] | ||
| ) | ||
| let output = try models.decoder.prediction(from: input) | ||
|
|
||
| guard let ctcLogits = output.featureValue(for: "ctc_logits")?.multiArrayValue else { | ||
| throw ASRError.processingFailed("Failed to extract ctc_logits from decoder") | ||
| } | ||
|
|
||
| return ctcLogits | ||
| } | ||
|
|
||
| private func greedyCtcDecode(logits: MLMultiArray) -> String { | ||
| // logits shape: [1, T, vocab_size+1] where T is time steps (188) | ||
| // vocab_size = 7000, blank_id = 7000 | ||
|
|
||
| let timeSteps = logits.shape[1].intValue | ||
| let vocabSize = logits.shape[2].intValue | ||
|
|
||
| var decoded: [Int] = [] | ||
| var prevLabel: Int? = nil | ||
|
|
||
| for t in 0..<timeSteps { | ||
| // Find argmax at this time step | ||
| var maxLogit: Float = -.infinity | ||
| var maxLabel = 0 | ||
|
|
||
| for v in 0..<vocabSize { | ||
| let logit = logits[[0, t as NSNumber, v as NSNumber]].floatValue | ||
| if logit > maxLogit { | ||
| maxLogit = logit | ||
| maxLabel = v | ||
| } | ||
| } | ||
|
|
||
| // CTC collapse: skip blanks and repeats | ||
| if maxLabel != models.blankId && maxLabel != prevLabel { | ||
| decoded.append(maxLabel) | ||
| } | ||
| prevLabel = maxLabel | ||
| } | ||
|
|
||
| // Convert token IDs to text | ||
| var text = "" | ||
| for tokenId in decoded { | ||
| if let token = models.vocabulary[tokenId] { | ||
| text += token | ||
| } | ||
| } | ||
|
|
||
| // Replace SentencePiece underscores with spaces | ||
| text = text.replacingOccurrences(of: "▁", with: " ") | ||
|
|
||
| return text.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| } | ||
|
|
||
| private func padOrTruncateAudio(_ audio: [Float], targetLength: Int) -> [Float] { | ||
| var result = audio | ||
| if result.count < targetLength { | ||
| // Pad with zeros | ||
| result.append(contentsOf: Array(repeating: 0.0, count: targetLength - result.count)) | ||
| } else if result.count > targetLength { | ||
| // Truncate | ||
| result = Array(result.prefix(targetLength)) | ||
| } | ||
| return result | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.