Swift에서 Whisper를 사용하는 가장 쉬운 방법
앱이나 패키지에 전사를 쉽게 추가하십시오. Whisper.cpp로 구동.
SwiftWhisper를 Package.swift 에서 종속성으로 추가하십시오. 스수프 파일 :
let package = Package (
...
dependencies : [
// Add the package to your dependencies
. package ( url : " https://github.com/exPHAT/SwiftWhisper.git " , branch : " master " ) ,
] ,
...
targets : [
// Add SwiftWhisper as a dependency on any target you want to use it in
. target ( name : " MyTarget " ,
dependencies : [ . byName ( name : " SwiftWhisper " ) ] )
]
...
) "Swift Package Manager"탭에 https://github.com/exPHAT/SwiftWhisper.git 추가하십시오.
API 문서.
import SwiftWhisper
let whisper = Whisper ( fromFileURL : /* Model file URL */ )
let segments = try await whisper . transcribe ( audioFrames : /* 16kHz PCM audio frames */ )
print ( " Transcribed audio: " , segments . map ( . text ) . joined ( ) ) WhisperDelegate 구현하고 whisper.delegate = ... 설정하여 세그먼트, 전사 진행 및 오류를 구독 할 수 있습니다.
protocol WhisperDelegate {
// Progress updates as a percentage from 0-1
func whisper ( _ aWhisper : Whisper , didUpdateProgress progress : Double )
// Any time a new segments of text have been transcribed
func whisper ( _ aWhisper : Whisper , didProcessNewSegments segments : [ Segment ] , atIndex index : Int )
// Finished transcribing, includes all transcribed segments of text
func whisper ( _ aWhisper : Whisper , didCompleteWithSegments segments : [ Segment ] )
// Error with transcription
func whisper ( _ aWhisper : Whisper , didErrorWith error : Error )
} 여기에서 미리 훈련 된 모델을 찾을 수 있습니다.
Coreml을 사용하려면 Whisper 모델과 동일한 이름으로 접미어 -encoder.mlmodelc 가있는 Coreml 모델 파일을 포함시켜야합니다 (예 : tiny.bin tiny-encoder.mlmodelc 파일 옆에 앉아 있습니다). 추가 모델 파일 외에도 Whisper(fromFileURL:) 이니셜 라이저를 사용해야합니다. 전사 중에 콘솔 출력을 확인하여 Coreml이 활성화되어 있는지 확인할 수 있습니다.
오디오 프레임을 Swiftwhisper로 가져 오는 가장 쉬운 방법은 Audiokit을 사용하는 것입니다. 다음 예제는 입력 오디오 파일을 사용하고 변환 및 리 샘플링하고 16kHz PCM 플로트 배열을 반환합니다.
import AudioKit
func convertAudioFileToPCMArray ( fileURL : URL , completionHandler : @escaping ( Result < [ Float ] , Error > ) -> Void ) {
var options = FormatConverter . Options ( )
options . format = . wav
options . sampleRate = 16000
options . bitDepth = 16
options . channels = 1
options . isInterleaved = false
let tempURL = URL ( fileURLWithPath : NSTemporaryDirectory ( ) ) . appendingPathComponent ( UUID ( ) . uuidString )
let converter = FormatConverter ( inputURL : fileURL , outputURL : tempURL , options : options )
converter . start { error in
if let error {
completionHandler ( . failure ( error ) )
return
}
let data = try ! Data ( contentsOf : tempURL ) // Handle error here
let floats = stride ( from : 44 , to : data . count , by : 2 ) . map {
return data [ $0 ..< $0 + 2 ] . withUnsafeBytes {
let short = Int16 ( littleEndian : $0 . load ( as : Int16 . self ) )
return max ( - 1.0 , min ( Float ( short ) / 32767.0 , 1.0 ) )
}
}
try ? FileManager . default . removeItem ( at : tempURL )
completionHandler ( . success ( floats ) )
}
} Debug 빌드 구성을 위해 앱을 컴파일 할 때 전사의 성능이 느려질 수 있습니다. 빌드 구성이 Release 되지 않으면 컴파일러가 SwiftWhisper를 완전히 최적화하지 않기 때문입니다.
.unsafeFlags(["-O3"]) 사용하여 최대 최적화를 강요하는 SwiftWhisper 버전을 설치 하여이 문제를 해결할 수 있습니다. 이를 수행하는 가장 쉬운 방법은 fast 지점에서 최신 커밋을 사용하는 것입니다. 또는 Release 구성에서 빌드 할 계획을 구성 할 수 있습니다.
...
dependencies: [
// Using latest commit hash for `fast` branch:
. package ( url : " https://github.com/exPHAT/SwiftWhisper.git " , revision : " deb1cb6a27256c7b01f5d3d2e7dc1dcc330b5d01 " ) ,
] ,
...