Repository navigation
Transcribe a selected audio track in local video and media #56
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
Changes from all commits
fca3fb3
8c53867
0bdda68
1582336
a5895d6
938cf9d
878e5fd
c69aba5
149545c
ec08f03
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| #if swift(>=6.4) | ||
| import AVFoundation | ||
| import CoreMedia | ||
| import Foundation | ||
| import Speech | ||
|
|
||
| @available(iOS 27.0, macOS 27.0, *) | ||
| public extension SpeechSession { | ||
| /// Stream transcription results from one audio track of a local media file, such as a movie. | ||
| /// | ||
| /// - Parameters: | ||
| /// - mediaFile: A local file URL in one of `options.allowedDirectories`. | ||
| /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. | ||
| /// - options: Contextual strings, allowed directories, and the maximum selected track duration. | ||
| /// - Returns: An async throwing stream of transcription results on the media timeline. | ||
| /// | ||
| /// The audio must be stored inside the media file and the session must use `.automatic` input. | ||
| func streamTranscription( | ||
| fromMediaFile mediaFile: URL, | ||
| audioTrackID: CMPersistentTrackID? = nil, | ||
| options: FileTranscriptionOptions = .init() | ||
| ) -> AsyncThrowingStream<SpeechTranscriber.Result, Error> { | ||
| startFileTranscription(mode: .mediaPlayback) { session, continuation, generation in | ||
| await session.startMediaFilePipeline( | ||
| mediaFile, audioTrackID: audioTrackID, options: options, | ||
| continuation: continuation, generation: generation | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @available(iOS 27.0, macOS 27.0, *) | ||
| private extension SpeechSession { | ||
| func startMediaFilePipeline( | ||
| _ mediaFile: URL, | ||
| audioTrackID: CMPersistentTrackID?, | ||
| options: FileTranscriptionOptions, | ||
| continuation: FileResultContinuation, | ||
| generation: Int | ||
| ) async { | ||
| do { | ||
| try Task.checkCancellation() | ||
| guard inputProviderPreference == .automatic else { | ||
| throw MediaTranscriptionConfigurationError() | ||
| } | ||
| let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) | ||
| let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) | ||
| let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) | ||
| try Task.checkCancellation() | ||
| try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") | ||
| try Task.checkCancellation() | ||
| try await setUpFilePipeline( | ||
| with: continuation, | ||
| contextualStrings: options.contextualStrings, | ||
| startAnalyzerImmediately: false, | ||
| mode: .mediaPlayback, | ||
| generation: generation | ||
| ) | ||
| try Task.checkCancellation() | ||
| guard let analyzer, let activeModules else { | ||
| throw SpeechSessionError.recognitionStreamSetupFailed | ||
| } | ||
| guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: activeModules) else { | ||
| throw SpeechSessionError.invalidAudioDataType | ||
| } | ||
| try Task.checkCancellation() | ||
| let provider = AssetInputSequenceProvider(asset: asset, track: track, analyzerFormat: format) | ||
| let inputs = provider.analyzerInputs | ||
| startFileIngestion(generation: generation) { session in | ||
| try await session.prepareAnalyzerForStartIfNeeded(in: format) | ||
| try Task.checkCancellation() | ||
| session.startSpeechDetectorMonitoringIfNeeded() | ||
|
|
||
| let endTime = try await analyzer.analyzeSequence(inputs) | ||
| try Task.checkCancellation() | ||
| if let endTime { | ||
| try await analyzer.finalizeAndFinish(through: endTime) | ||
| } else { | ||
| // With no input samples, Speech may leave the module's results stream open. | ||
| session.prepareForStop() | ||
| await session.cleanup(cancelRecognizer: true, generation: generation) | ||
| await session.finishStream(error: nil, generation: generation) | ||
| } | ||
| } | ||
| } catch { | ||
| await finishFailedPipelineSetup(error, generation: generation) | ||
| } | ||
| } | ||
|
|
||
| static func makeMediaAsset(url: URL, needsPreciseDuration: Bool) -> AVURLAsset { | ||
| var options: [String: Any] = [ | ||
| AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue | ||
| ] | ||
| if needsPreciseDuration { | ||
| options[AVURLAssetPreferPreciseDurationAndTimingKey] = true | ||
| } | ||
| return AVURLAsset(url: url, options: options) | ||
| } | ||
|
|
||
| func loadAudioTrack( | ||
| from asset: AVAsset, | ||
| id: CMPersistentTrackID?, | ||
| maxDuration: TimeInterval? | ||
| ) async throws -> AVAssetTrack { | ||
| let tracks = try await asset.loadTracks(withMediaType: .audio) | ||
| guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { | ||
| let reason = if let id { | ||
| String.localizedStringWithFormat(NSLocalizedString( | ||
| "audio track ID %d was not found", comment: "The requested audio track is missing" | ||
| ), id) | ||
| } else { | ||
| NSLocalizedString("the media file has no audio tracks", comment: "The media asset has no audio track") | ||
| } | ||
| throw SpeechSessionError.audioFileUnsupportedFormat(reason) | ||
| } | ||
| let duration = try await track.load(.timeRange).duration.seconds | ||
| guard duration.isFinite, duration > 0 else { | ||
| throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( | ||
| "the audio track has no finite, positive duration", | ||
| comment: "The media audio track has no usable duration" | ||
| )) | ||
| } | ||
| if let maxDuration, duration > maxDuration { | ||
| throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) | ||
| } | ||
| return track | ||
| } | ||
| } | ||
|
|
||
| private struct MediaTranscriptionConfigurationError: LocalizedError { | ||
| var errorDescription: String? { | ||
| NSLocalizedString( | ||
| "Media transcription requires the automatic input provider.", | ||
| comment: "Media files cannot use the legacy audio input pipeline" | ||
| ) | ||
| } | ||
|
|
||
| var recoverySuggestion: String? { | ||
| NSLocalizedString( | ||
| "Create a SpeechSession with inputProviderPreference set to .automatic.", | ||
| comment: "How to enable media transcription" | ||
| ) | ||
| } | ||
| } | ||
| #endif | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -296,6 +296,7 @@ extension SpeechSession { | |
| task?.cancel() | ||
| } | ||
|
|
||
| let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback | ||
| streamingMode = .inactive | ||
| activeResultKind = nil | ||
| stopAudioStreaming() | ||
|
|
@@ -306,7 +307,7 @@ extension SpeechSession { | |
| #endif | ||
| let detached = detachTranscriberState() | ||
| await stopScreenCaptureStreamingIfNeeded() | ||
| await finalizeDetachedTranscriberState(detached) | ||
| await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stop cancel limited to mediaHigh Severity
Additional Locations (1)Reviewed by Cursor Bugbot for commit 149545c. Configure here. |
||
|
|
||
| guard generation == sessionGeneration else { return } | ||
| await modelManager.releaseLocales() | ||
|
|
@@ -443,6 +444,7 @@ extension SpeechSession { | |
| for try await result in results { | ||
| streamContinuation.yield(result) | ||
| } | ||
| try Task.checkCancellation() | ||
| if Self.shouldLog(.notice) { | ||
| Self.logger.notice("\(label, privacy: .public) completed without error") | ||
| } | ||
|
|
@@ -452,6 +454,7 @@ extension SpeechSession { | |
| Self.logger.debug("\(label, privacy: .public) cancelled") | ||
| } | ||
| } catch { | ||
| guard !Task.isCancelled else { return } | ||
| if Self.shouldLog(.error) { | ||
| Self.logger.error( | ||
| "\(label, privacy: .public) failed: \(error.localizedDescription, privacy: .public)" | ||
|
|
||


There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Private error skips SpeechSessionError
Medium Severity
A non-automatic
inputProviderPreferencenow throws privateMediaTranscriptionConfigurationErrorinstead ofSpeechSessionError. Callers that catchSpeechSessionError(as the public docs describe) miss this failure, and the type is not visible outside the module so it cannot be handled by name.Additional Locations (1)
Sources/AuralKit/SpeechSession+MediaFile.swift#L129-L144Reviewed by Cursor Bugbot for commit 149545c. Configure here.