-
Notifications
You must be signed in to change notification settings - Fork 266
/
ContentView.swift
1149 lines (1025 loc) · 47.5 KB
/
ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// For licensing see accompanying LICENSE.md file.
// Copyright © 2024 Argmax, Inc. All rights reserved.
import SwiftUI
import WhisperKit
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
import AVFoundation
struct ContentView: View {
@State var whisperKit: WhisperKit? = nil
#if os(macOS)
@State var audioDevices: [AudioDevice]? = nil
#endif
@State var isRecording: Bool = false
@State var isTranscribing: Bool = false
@State var currentText: String = ""
// TODO: Make this configurable in the UI
@State var modelStorage: String = "huggingface/models/argmaxinc/whisperkit-coreml"
@State private var modelState: ModelState = .unloaded
@State private var localModels: [String] = []
@State private var localModelPath: String = ""
@State private var availableModels: [String] = []
@State private var availableLanguages: [String] = []
@State private var disabledModels: [String] = WhisperKit.recommendedModels().disabled
@AppStorage("selectedAudioInput") private var selectedAudioInput: String = "No Audio Input"
@AppStorage("selectedModel") private var selectedModel: String = WhisperKit.recommendedModels().default
@AppStorage("selectedTab") private var selectedTab: String = "Transcribe"
@AppStorage("selectedTask") private var selectedTask: String = "transcribe"
@AppStorage("selectedLanguage") private var selectedLanguage: String = "english"
@AppStorage("repoName") private var repoName: String = "argmaxinc/whisperkit-coreml"
@AppStorage("enableTimestamps") private var enableTimestamps: Bool = true
@AppStorage("enablePromptPrefill") private var enablePromptPrefill: Bool = true
@AppStorage("enableCachePrefill") private var enableCachePrefill: Bool = true
@AppStorage("enableSpecialCharacters") private var enableSpecialCharacters: Bool = false
@AppStorage("enableEagerDecoder") private var enableEagerDecoder: Bool = false
@AppStorage("temperatureStart") private var temperatureStart: Double = 0
@AppStorage("fallbackCount") private var fallbackCount: Double = 4
@AppStorage("compressionCheckWindow") private var compressionCheckWindow: Double = 20
@AppStorage("sampleLength") private var sampleLength: Double = 224
@AppStorage("silenceThreshold") private var silenceThreshold: Double = 0.3
@AppStorage("useVAD") private var useVAD: Bool = true
@State private var loadingProgressValue: Float = 0.0
@State private var specializationProgressRatio: Float = 0.7
@State private var isFilePickerPresented = false
@State private var firstTokenTime: TimeInterval = 0
@State private var pipelineStart: TimeInterval = 0
@State private var realTimeFactor: TimeInterval = 0
@State private var tokensPerSecond: TimeInterval = 0
@State private var currentLag: TimeInterval = 0
@State private var currentFallbacks: Int = 0
@State private var lastBufferSize: Int = 0
@State private var lastConfirmedSegmentEndSeconds: Float = 0
@State private var requiredSegmentsForConfirmation: Int = 2
@State private var bufferEnergy: [Float] = []
@State private var confirmedSegments: [TranscriptionSegment] = []
@State private var unconfirmedSegments: [TranscriptionSegment] = []
@State private var unconfirmedText: [String] = []
@State private var showAdvancedOptions: Bool = false
@State private var transcriptionTask: Task<Void, Never>? = nil
@State private var selectedCategoryId: MenuItem.ID?
private var menu = [
MenuItem(name: "Transcribe", image: "book.pages"),
MenuItem(name: "Stream", image: "waveform.badge.mic"),
]
struct MenuItem: Identifiable, Hashable {
var id = UUID()
var name: String
var image: String
}
// MARK: Views
func resetState() {
isRecording = false
isTranscribing = false
whisperKit?.audioProcessor.stopRecording()
currentText = ""
unconfirmedText = []
firstTokenTime = 0
pipelineStart = 0
realTimeFactor = 0
tokensPerSecond = 0
currentLag = 0
currentFallbacks = 0
lastBufferSize = 0
lastConfirmedSegmentEndSeconds = 0
requiredSegmentsForConfirmation = 2
bufferEnergy = []
confirmedSegments = []
unconfirmedSegments = []
}
var body: some View {
NavigationSplitView(columnVisibility: Binding.constant(.all)) {
modelSelectorView
.padding()
Spacer()
List(menu, selection: $selectedCategoryId) { item in
HStack {
Image(systemName: item.image)
Text(item.name)
.font(.system(.title3))
.bold()
}
}
.disabled(modelState != .loaded)
.foregroundColor(modelState != .loaded ? .secondary : .primary)
.navigationTitle("WhisperAX")
.navigationSplitViewColumnWidth(min: 300, ideal: 350)
} detail: {
VStack {
#if os(iOS)
modelSelectorView
.padding()
transcriptionView
#elseif os(macOS)
VStack(alignment: .leading) {
transcriptionView
}
.padding()
#endif
controlsView
}
.toolbar(content: {
ToolbarItem {
Button {
let fullTranscript = formatSegments(confirmedSegments + unconfirmedSegments, withTimestamps: enableTimestamps).joined(separator: "\n")
#if os(iOS)
UIPasteboard.general.string = fullTranscript
#elseif os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(fullTranscript, forType: .string)
#endif
} label: {
Label("Copy Text", systemImage: "doc.on.doc")
}
.foregroundColor(.primary)
.frame(minWidth: 0, maxWidth: .infinity)
}
})
}
.onAppear {
#if os(macOS)
selectedCategoryId = menu.first(where: { $0.name == selectedTab })?.id
#endif
fetchModels()
}
}
// MARK: - Transcription
var transcriptionView: some View {
VStack {
ScrollView(.horizontal) {
HStack(spacing: 1) {
let startIndex = max(bufferEnergy.count - 300, 0)
ForEach(Array(bufferEnergy.enumerated())[startIndex...], id: \.element) { _, energy in
ZStack {
RoundedRectangle(cornerRadius: 2)
.frame(width: 2, height: CGFloat(energy) * 24)
}
.frame(maxHeight: 24)
.background(energy > Float(silenceThreshold) ? Color.green.opacity(0.2) : Color.red.opacity(0.2))
}
}
}
.defaultScrollAnchor(.trailing)
.frame(height: 24)
.scrollIndicators(.never)
ScrollView {
VStack(alignment: .leading) {
ForEach(Array(confirmedSegments.enumerated()), id: \.element) { _, segment in
let timestampText = enableTimestamps ? "[\(String(format: "%.2f", segment.start)) --> \(String(format: "%.2f", segment.end))]" : ""
Text(timestampText + segment.text)
.font(.headline)
.fontWeight(.bold)
.tint(.green)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
ForEach(Array(unconfirmedSegments.enumerated()), id: \.element) { _, segment in
let timestampText = enableTimestamps ? "[\(String(format: "%.2f", segment.start)) --> \(String(format: "%.2f", segment.end))]" : ""
Text(timestampText + segment.text)
.font(.headline)
.fontWeight(.light)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
Text("\(unconfirmedText.joined(separator: "\n"))")
.font(.caption)
.foregroundColor(.secondary)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
Text("\(currentText)")
.font(.caption)
.foregroundColor(.secondary)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.frame(maxWidth: .infinity)
.defaultScrollAnchor(.bottom)
.padding()
}
}
// MARK: - Models
var modelSelectorView: some View {
Group {
VStack {
HStack {
Image(systemName: "circle.fill")
.foregroundStyle(modelState == .loaded ? .green : (modelState == .unloaded ? .red : .yellow))
.symbolEffect(.variableColor, isActive: modelState != .loaded && modelState != .unloaded)
Text(modelState.description)
Spacer()
if availableModels.count > 0 {
Picker("", selection: $selectedModel) {
ForEach(availableModels, id: \.self) { model in
HStack {
let modelIcon = localModels.contains { $0 == model.description } ? "checkmark.circle" : "arrow.down.circle.dotted"
Text("\(Image(systemName: modelIcon)) \(model.description)").tag(model.description)
}
}
}
.pickerStyle(MenuPickerStyle())
.onChange(of: selectedModel, initial: false) { _, _ in
modelState = .unloaded
}
} else {
ProgressView()
.progressViewStyle(CircularProgressViewStyle())
.scaleEffect(0.5)
}
#if os(macOS)
Button(action: {
if let folder = whisperKit?.modelFolder {
NSWorkspace.shared.open(folder)
}
}, label: {
Image(systemName: "folder")
})
.buttonStyle(BorderlessButtonStyle())
#endif
Button(action: {
if let url = URL(string: "https://huggingface.co/\(repoName)") {
#if os(macOS)
NSWorkspace.shared.open(url)
#else
UIApplication.shared.open(url)
#endif
}
}, label: {
Image(systemName: "link.circle")
})
.buttonStyle(BorderlessButtonStyle())
}
if modelState == .unloaded {
Divider()
Button {
resetState()
loadModel(selectedModel)
modelState = .loading
} label: {
Text("Load Model")
.frame(maxWidth: .infinity)
.frame(height: 40)
}
.buttonStyle(.borderedProminent)
} else if loadingProgressValue < 1.0 {
VStack {
HStack {
ProgressView(value: loadingProgressValue, total: 1.0)
.progressViewStyle(LinearProgressViewStyle())
.frame(maxWidth: .infinity)
Text(String(format: "%.1f%%", loadingProgressValue * 100))
.font(.caption)
.foregroundColor(.gray)
}
if modelState == .prewarming {
Text("Specializing \(selectedModel) for your device...\nThis can take several minutes on first load")
.font(.caption)
.foregroundColor(.gray)
}
}
}
}
}
}
// MARK: - Controls
var controlsView: some View {
VStack {
basicSettingsView
if let selectedCategoryId, let item = menu.first(where: { $0.id == selectedCategoryId }) {
switch item.name {
case "Transcribe":
VStack {
HStack {
Button {
resetState()
} label: {
Label("Reset", systemImage: "arrow.clockwise")
}
.buttonStyle(.borderless)
Spacer()
Button {
showAdvancedOptions.toggle()
} label: {
Label("Settings", systemImage: "slider.horizontal.3")
}
.buttonStyle(.borderless)
}
HStack {
let color: Color = modelState != .loaded ? .gray : .red
Button(action: {
withAnimation {
selectFile()
}
}) {
Text("FROM FILE")
.font(.headline)
.foregroundColor(color)
.padding()
.cornerRadius(40)
.frame(minWidth: 70, minHeight: 70)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(color, lineWidth: 4)
)
}
.fileImporter(
isPresented: $isFilePickerPresented,
allowedContentTypes: [.audio],
allowsMultipleSelection: false,
onCompletion: handleFilePicker
)
.lineLimit(1)
.contentTransition(.symbolEffect(.replace))
.buttonStyle(BorderlessButtonStyle())
.disabled(modelState != .loaded)
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
Button(action: {
withAnimation {
toggleRecording(shouldLoop: false)
}
}) {
if !isRecording {
Text("RECORD")
.font(.headline)
.foregroundColor(color)
.padding()
.cornerRadius(40)
.frame(minWidth: 70, minHeight: 70)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(color, lineWidth: 4)
)
} else {
Image(systemName: "stop.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 70, height: 70)
.padding()
.foregroundColor(modelState != .loaded ? .gray : .red)
}
}
.lineLimit(1)
.contentTransition(.symbolEffect(.replace))
.buttonStyle(BorderlessButtonStyle())
.disabled(modelState != .loaded)
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
}
}
case "Stream":
HStack {
Button {
resetState()
} label: {
Label("Reset", systemImage: "arrow.clockwise")
}
.frame(minWidth: 0, maxWidth: .infinity)
.buttonStyle(.borderless)
Button {
withAnimation {
toggleRecording(shouldLoop: true)
}
} label: {
Image(systemName: !isRecording ? "record.circle" : "stop.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 70, height: 70)
.padding()
.foregroundColor(modelState != .loaded ? .gray : .red)
}
.contentTransition(.symbolEffect(.replace))
.buttonStyle(BorderlessButtonStyle())
.disabled(modelState != .loaded)
.frame(minWidth: 0, maxWidth: .infinity)
VStack {
Button {
showAdvancedOptions.toggle()
} label: {
Label("Settings", systemImage: "slider.horizontal.3")
}
.frame(minWidth: 0, maxWidth: .infinity)
.buttonStyle(.borderless)
#if os(macOS)
HStack {
if let audioDevices = audioDevices, audioDevices.count > 0 {
Picker("", selection: $selectedAudioInput) {
ForEach(audioDevices, id: \.self) { device in
Text(device.name).tag(device.name)
}
}
.frame(minWidth: 80)
.disabled(isRecording)
}
}
.onAppear {
audioDevices = AudioProcessor.getAudioDevices()
if let audioDevices = audioDevices,
!audioDevices.isEmpty,
selectedAudioInput == "No Audio Input",
let device = audioDevices.first {
selectedAudioInput = device.name
}
}
#endif
}
}
default:
EmptyView()
}
}
}
.frame(maxWidth: .infinity)
.padding(.horizontal)
.sheet(isPresented: $showAdvancedOptions, content: {
advancedSettingsView
.presentationDetents([.medium, .large])
.presentationBackgroundInteraction(.enabled)
.presentationContentInteraction(.scrolls)
})
}
var basicSettingsView: some View {
VStack {
HStack {
Picker("", selection: $selectedTask) {
ForEach(DecodingTask.allCases, id: \.self) { task in
Text(task.description.capitalized).tag(task.description)
}
}
.pickerStyle(SegmentedPickerStyle())
.disabled(!(whisperKit?.modelVariant.isMultilingual ?? false))
}
.padding(.horizontal)
LabeledContent {
Picker("", selection: $selectedLanguage) {
ForEach(availableLanguages, id: \.self) { language in
Text(language.description).tag(language.description)
}
}
.disabled(!(whisperKit?.modelVariant.isMultilingual ?? false))
} label: {
Label("Language", systemImage: "globe")
}
.padding(.horizontal)
.padding(.top)
HStack {
Text(realTimeFactor.formatted(.number.precision(.fractionLength(3))) + " RTF")
.font(.system(.body))
.lineLimit(1)
Spacer()
Text(tokensPerSecond.formatted(.number.precision(.fractionLength(0))) + " tok/s")
.font(.system(.body))
.lineLimit(1)
Spacer()
Text("First token: " + (firstTokenTime - pipelineStart).formatted(.number.precision(.fractionLength(2))) + "s")
.font(.system(.body))
.lineLimit(1)
}
.padding()
.frame(maxWidth: .infinity)
}
}
var advancedSettingsView: some View {
#if os(iOS)
NavigationView {
settingsForm
.navigationBarTitleDisplayMode(.inline)
}
#else
VStack {
Text("Decoding Options")
.font(.title2)
.padding()
settingsForm
.frame(minWidth: 500, minHeight: 500)
}
#endif
}
var settingsForm: some View {
List {
HStack {
Text("Show Timestamps")
InfoButton("Toggling this will include/exclude timestamps in both the UI and the prefill tokens.\nEither <|notimestamps|> or <|0.00|> will be forced based on this setting unless \"Prompt Prefill\" is de-selected.")
Spacer()
Toggle("", isOn: $enableTimestamps)
}
.padding(.horizontal)
HStack {
Text("Special Characters")
InfoButton("Toggling this will include/exclude special characters in the transcription text.")
Spacer()
Toggle("", isOn: $enableSpecialCharacters)
}
.padding(.horizontal)
HStack {
Text("Prompt Prefill")
InfoButton("When Prompt Prefill is on, it will force the task, language, and timestamp tokens in the decoding loop. \nToggle it off if you'd like the model to generate those tokens itself instead.")
Spacer()
Toggle("", isOn: $enablePromptPrefill)
}
.padding(.horizontal)
HStack {
Text("Cache Prefill")
InfoButton("When Cache Prefill is on, the decoder will try to use a lookup table of pre-computed KV caches instead of computing them during the decoding loop. \nThis allows the model to skip the compute required to force the initial prefill tokens, and can speed up inference")
Spacer()
Toggle("", isOn: $enableCachePrefill)
}
.padding(.horizontal)
VStack {
Text("Starting Temperature:")
HStack {
Slider(value: $temperatureStart, in: 0...1, step: 0.1)
Text(temperatureStart.formatted(.number))
InfoButton("Controls the initial randomness of the decoding loop token selection.\nA higher temperature will result in more random choices for tokens, and can improve accuracy.")
}
}
.padding(.horizontal)
VStack {
Text("Max Fallback Count:")
HStack {
Slider(value: $fallbackCount, in: 0...5, step: 1)
Text(fallbackCount.formatted(.number))
.frame(width: 30)
InfoButton("Controls how many times the decoder will fallback to a higher temperature if any of the decoding thresholds are exceeded.\n Higher values will cause the decoder to run multiple times on the same audio, which can improve accuracy at the cost of speed.")
}
}
.padding(.horizontal)
VStack {
Text("Compression Check Tokens")
HStack {
Slider(value: $compressionCheckWindow, in: 0...100, step: 5)
Text(compressionCheckWindow.formatted(.number))
.frame(width: 30)
InfoButton("Amount of tokens to use when checking for whether the model is stuck in a repetition loop.\nRepetition is checked by using zlib compressed size of the text compared to non-compressed value.\n Lower values will catch repetitions sooner, but too low will miss repetition loops of phrases longer than the window.")
}
}
.padding(.horizontal)
VStack {
Text("Max Tokens Per Loop")
HStack {
Slider(value: $sampleLength, in: 0...Double(min(whisperKit?.textDecoder.kvCacheMaxSequenceLength ?? WhisperKit.maxTokenContext, WhisperKit.maxTokenContext)), step: 10)
Text(sampleLength.formatted(.number))
.frame(width: 30)
InfoButton("Maximum number of tokens to generate per loop.\nCan be lowered based on the type of speech in order to further prevent repetition loops from going too long.")
}
}
.padding(.horizontal)
VStack {
Text("Silence Threshold")
HStack {
Slider(value: $silenceThreshold, in: 0...1, step: 0.05)
Text(silenceThreshold.formatted(.number))
.frame(width: 30)
InfoButton("Relative silence threshold for the audio. \n Baseline is set by the quietest 100ms in the previous 2 seconds.")
}
}
.padding(.horizontal)
}
.navigationTitle("Decoding Options")
.toolbar(content: {
ToolbarItem {
Button {
showAdvancedOptions = false
} label: {
Label("Done", systemImage: "xmark.circle.fill")
.foregroundColor(.primary)
}
}
})
}
struct InfoButton: View {
var infoText: String
@State private var showInfo = false
init(_ infoText: String) {
self.infoText = infoText
}
var body: some View {
Button(action: {
self.showInfo = true
}) {
Image(systemName: "info.circle")
.foregroundColor(.blue)
}
.popover(isPresented: $showInfo) {
Text(infoText)
.padding()
}
.buttonStyle(BorderlessButtonStyle())
}
}
// MARK: Logic
func fetchModels() {
availableModels = [selectedModel]
// First check what's already downloaded
if let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let modelPath = documents.appendingPathComponent(modelStorage).path
// Check if the directory exists
if FileManager.default.fileExists(atPath: modelPath) {
localModelPath = modelPath
do {
let downloadedModels = try FileManager.default.contentsOfDirectory(atPath: modelPath)
for model in downloadedModels where !localModels.contains(model) && model.starts(with: "openai") {
localModels.append(model)
}
} catch {
print("Error enumerating files at \(modelPath): \(error.localizedDescription)")
}
}
}
localModels = WhisperKit.formatModelFiles(localModels)
for model in localModels {
if !availableModels.contains(model),
!disabledModels.contains(model)
{
availableModels.append(model)
}
}
print("Found locally: \(localModels)")
print("Previously selected model: \(selectedModel)")
Task {
let remoteModels = try await WhisperKit.fetchAvailableModels(from: repoName)
for model in remoteModels {
if !availableModels.contains(model),
!disabledModels.contains(model)
{
availableModels.append(model)
}
}
}
}
func loadModel(_ model: String, redownload: Bool = false) {
print("Selected Model: \(UserDefaults.standard.string(forKey: "selectedModel") ?? "nil")")
whisperKit = nil
Task {
whisperKit = try await WhisperKit(
verbose: true,
logLevel: .debug,
prewarm: false,
load: false,
download: false
)
guard let whisperKit = whisperKit else {
return
}
var folder: URL?
// Check if the model is available locally
if localModels.contains(model) && !redownload {
// Get local model folder URL from localModels
// TODO: Make this configurable in the UI
folder = URL(fileURLWithPath: localModelPath).appendingPathComponent("openai_whisper-\(model)")
} else {
// Download the model
folder = try await WhisperKit.download(variant: model, from: repoName, progressCallback: { progress in
DispatchQueue.main.async {
loadingProgressValue = Float(progress.fractionCompleted) * specializationProgressRatio
modelState = .downloading
}
})
}
await MainActor.run {
loadingProgressValue = specializationProgressRatio
modelState = .downloaded
}
if let modelFolder = folder {
whisperKit.modelFolder = modelFolder
await MainActor.run {
// Set the loading progress to 90% of the way after prewarm
loadingProgressValue = specializationProgressRatio
modelState = .prewarming
}
let progressBarTask = Task {
await updateProgressBar(targetProgress: 0.9, maxTime: 240)
}
// Prewarm models
do {
try await whisperKit.prewarmModels()
progressBarTask.cancel()
} catch {
print("Error prewarming models, retrying: \(error.localizedDescription)")
progressBarTask.cancel()
if !redownload {
loadModel(model, redownload: true)
return
} else {
// Redownloading failed, error out
modelState = .unloaded
return
}
}
await MainActor.run {
// Set the loading progress to 90% of the way after prewarm
loadingProgressValue = specializationProgressRatio + 0.9 * (1 - specializationProgressRatio)
modelState = .loading
}
try await whisperKit.loadModels()
await MainActor.run {
availableLanguages = whisperKit.tokenizer?.langauges.map { $0.key }.sorted() ?? ["english"]
loadingProgressValue = 1.0
modelState = whisperKit.modelState
}
}
}
}
func updateProgressBar(targetProgress: Float, maxTime: TimeInterval) async {
let initialProgress = loadingProgressValue
let decayConstant = -log(1 - targetProgress) / Float(maxTime)
let startTime = Date()
while true {
let elapsedTime = Date().timeIntervalSince(startTime)
// Break down the calculation
let decayFactor = exp(-decayConstant * Float(elapsedTime))
let progressIncrement = (1 - initialProgress) * (1 - decayFactor)
let currentProgress = initialProgress + progressIncrement
await MainActor.run {
loadingProgressValue = currentProgress
}
if currentProgress >= targetProgress {
break
}
do {
try await Task.sleep(nanoseconds: 100_000_000)
} catch {
break
}
}
}
func selectFile() {
isFilePickerPresented = true
}
func handleFilePicker(result: Result<[URL], Error>) {
switch result {
case let .success(urls):
guard let selectedFileURL = urls.first else { return }
if selectedFileURL.startAccessingSecurityScopedResource() {
do {
// Access the document data from the file URL
let audioFileData = try Data(contentsOf: selectedFileURL)
// Create a unique file name to avoid overwriting any existing files
let uniqueFileName = UUID().uuidString + "." + selectedFileURL.pathExtension
// Construct the temporary file URL in the app's temp directory
let tempDirectoryURL = FileManager.default.temporaryDirectory
let localFileURL = tempDirectoryURL.appendingPathComponent(uniqueFileName)
// Write the data to the temp directory
try audioFileData.write(to: localFileURL)
print("File saved to temporary directory: \(localFileURL)")
transcribeFile(path: selectedFileURL.path)
} catch {
print("File selection error: \(error.localizedDescription)")
}
}
case let .failure(error):
print("File selection error: \(error.localizedDescription)")
}
}
func transcribeFile(path: String) {
resetState()
whisperKit?.audioProcessor = AudioProcessor()
Task {
do {
try await transcribeCurrentFile(path: path)
} catch {
print("File selection error: \(error.localizedDescription)")
}
}
}
func toggleRecording(shouldLoop: Bool) {
isRecording.toggle()
if isRecording {
resetState()
startRecording(shouldLoop)
} else {
stopRecording(shouldLoop)
}
}
func startRecording(_ loop: Bool) {
if let audioProcessor = whisperKit?.audioProcessor {
Task(priority: .userInitiated) {
guard await AudioProcessor.requestRecordPermission() else {
print("Microphone access was not granted.")
return
}
var deviceId: DeviceID?
#if os(macOS)
if self.selectedAudioInput != "No Audio Input",
let devices = self.audioDevices,
let device = devices.first(where: {$0.name == selectedAudioInput}) {
deviceId = device.id
}
#endif
try? audioProcessor.startRecordingLive(inputDeviceID: deviceId) { _ in
DispatchQueue.main.async {
bufferEnergy = whisperKit?.audioProcessor.relativeEnergy ?? []
}
}
// Delay the timer start by 1 second
isRecording = true
isTranscribing = true
if loop {
realtimeLoop()
}
}
}
}
func stopRecording(_ loop: Bool) {
isRecording = false
stopRealtimeTranscription()
if let audioProcessor = whisperKit?.audioProcessor {
audioProcessor.stopRecording()
}
// If not looping, transcribe the full buffer
if !loop {
Task {
do {
try await transcribeCurrentBuffer()
} catch {
print("Error: \(error.localizedDescription)")
}
}
}
}
// MARK: Transcribe Logic
func transcribeCurrentFile(path: String) async throws {
guard let audioFileBuffer = AudioProcessor.loadAudio(fromPath: path) else {
return
}
let audioFileSamples = AudioProcessor.convertBufferToArray(buffer: audioFileBuffer)
let transcription = try await transcribeAudioSamples(audioFileSamples)
await MainActor.run {
currentText = ""
unconfirmedText = []
guard let segments = transcription?.segments else {
return
}
self.tokensPerSecond = transcription?.timings?.tokensPerSecond ?? 0
self.realTimeFactor = transcription?.timings?.realTimeFactor ?? 0
self.firstTokenTime = transcription?.timings?.firstTokenTime ?? 0
self.pipelineStart = transcription?.timings?.pipelineStart ?? 0
self.currentLag = transcription?.timings?.decodingLoop ?? 0
self.confirmedSegments = segments
}
}
func transcribeAudioSamples(_ samples: [Float]) async throws -> TranscriptionResult? {
guard let whisperKit = whisperKit else { return nil }
let languageCode = whisperKit.tokenizer?.langauges[selectedLanguage] ?? "en"
let task: DecodingTask = selectedTask == "transcribe" ? .transcribe : .translate
let seekClip = [lastConfirmedSegmentEndSeconds]
let options = DecodingOptions(
verbose: false,
task: task,
language: languageCode,
temperatureFallbackCount: 3, // limit fallbacks for realtime
sampleLength: Int(sampleLength), // reduced sample length for realtime
usePrefillPrompt: enablePromptPrefill,
usePrefillCache: enableCachePrefill,
skipSpecialTokens: !enableSpecialCharacters,
withoutTimestamps: !enableTimestamps,
clipTimestamps: seekClip
)
// Early stopping checks
let decodingCallback: ((TranscriptionProgress) -> Bool?) = { progress in
DispatchQueue.main.async {
let fallbacks = Int(progress.timings.totalDecodingFallbacks)
if progress.text.count < currentText.count {
if fallbacks == self.currentFallbacks {
self.unconfirmedText.append(currentText)
} else {
print("Fallback occured: \(fallbacks)")
}
}
self.currentText = progress.text
self.currentFallbacks = fallbacks
}
// Check early stopping
let currentTokens = progress.tokens
let checkWindow = Int(compressionCheckWindow)
if currentTokens.count > checkWindow {
let checkTokens: [Int] = currentTokens.suffix(checkWindow)
let compressionRatio = compressionRatio(of: checkTokens)
if compressionRatio > options.compressionRatioThreshold! {
return false
}
}